1、问题
自定义类需要表示它所要建模的实体的属性。
2、解决方案
需要在类接口中声明属性,然后在类实现中实现这些属性。
3、原理
在自定义类的头文件中,你需要两个东西:保存属性的实例变量值、属性声明。例如:
#import <Foundation/Foundation.h>
@interface Car : NSObject {
@private
NSString *name_;
}
@property(strong) NSString *name;
@end
这里的本地实例叫做name_,属性的声明以@property开头。注意在类名NSString前有(strong),strong就是property attribute,strong只是许多property描述符中的一个。
=============================================================================================
Table 1-2. Property Attributes
Attribute Description
readwrite The property needs both a getter and a setter (default).
readonly The property only needs a getter (objects can’t set this property).
strong The property will have a strong relationship (the object will be retained).
weak The property will be set to nil when the destination object is deallocated.
assign The property will simply use assignment (used with primitive types).
copy The property returns a copy and must implement the NSCopying protocol.
retain A retain message will be sent in the setter method.
nonatomic This specifies that the property is not atomic (not locked while being accessed).
==============================================================================================
在实现类中实现属性,编写所谓的getters和setters。
#import "Car.h"
@implementation Car
-(void)setName:(NSString *) name {
name_ = name;
}
-(NSString *) name {
return name_;
}
@end
// 调用代码
car.name = @"Sports Car";
NSLog(@"car is %@", car.name);
Or you can use properties with standard Objective-C messaging:
[car setName:@"New Car Name"];
NSLog(@"car.name is %@", [car name]);
Dot notation(第1个例子)是一个相对新一些的Objective-C特性,Objective-C 2.0引入。优势是在其他编程语言中,这很常见,所以你对此很熟悉。
第2种写法是平常的Objective-C messaging,也常常用。
选择哪个,就要根据你的个人偏好。
4、代码
#import "Car.h"
int main (int argc, const char * argv[]){
@autoreleasepool {
Car *car = [[Car alloc] init];
car.name = @"Sports Car";
NSLog(@"car.name is %@", car.name);
[car setName:@"New Car Name"];
NSLog(@"car.name is %@", [car name]);
}
return 0;
}