您的位置:首页 > 移动开发 > Objective-C

[Objective-C] class add a property and its setter and getter

2015-06-29 18:28 609 查看
参考:

http://cocoadevcentral.com/d/learn_objectivec/

/article/1227605.html

http://www.88cto.com/996655/article/details/21674.html

/article/8320208.html

有两种方法,方法一较简洁方便,方法二较灵活。

方法一:

使用 @property 和 @synthesize 关键字。setter 和 getter 方法会编译器被自动生成。详情参考 [Objective-C]property setter/getter via @property

// ========= Person.h =========
@interface Person: NSObject
{
}
-(id) Print;
@property NSString* name;
@end

// ========= Person.m =========
#import "Person.h"
@implementation Person
-(id) Print {
NSLog(@"Print_Name:%@", _name);    // #100
}
@end

// ========= main.mm =========
#import <Foundation/Foundation.h>
#import "Person.h"

int main(int argc, const char * argv[]) {
@autoreleasepool {
Person* p = [[Person alloc] init];
[p setName:@"Henry"];
NSLog(@"Name:%@", [p name]);
[p Print];
}
}


方法二:

自己定义property、setter方法、getter方法。

// MyTest.h

#import <Foundation/Foundation.h>

@interface MyTest : NSObject
{
NSString* caption; // caption MUST be declared here
}

- (NSString*) caption;

- (void) setCaption: (NSString*) input;

@end
// MyTest.h

#import "MyTest.h"

@implementation MyTest
{

}

- (NSString*) caption {
return caption;
}

- (void) setCaption: (NSString*) input {
caption = input;
}

@end


注:

Object C的类的getter函数省略了getXXX的"get",比如类的某属性叫caption,getter函数也叫caption。setter函数叫setCaption
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: