property 经常使用的是在class中的@interface 块中
@interface MyClass : NSObject
@property (nonatomic, copy) NSString *name;
@end
自动会生成一对访问器setter/getter 和一个成员变量即
// setter
-(void)setName:(NSString *)name{
}
//getter
-(NSString *)name{
}
//成员变量
_name
默认情况下setter是 set+ 熟悉名(首字母写),getter是熟悉名 成员变量是_+熟悉名
通过以下代码可以验证:
//查看所有方法和成员变量
unsigned int methodCount = 0;
Method *methods = class_copyMethodList(MyClass.class, &methodCount);
for (int i = 0; i < methodCount; i++) {
Method method = methods[i];
SEL sel = method_getName(method);
const char *methodName = sel_getName(sel);
NSLog(@"%@",[NSString stringWithUTF8String:methodName]);
}
//输出: setName: 和 name
unsigned int ivarCount = 0;
Ivar *ivars = class_copyIvarList(MyClass.class, &ivarCount);
for (int i = 0; i < ivarCount; i++) {
Ivar ivar = ivars[i];
const char *ivarName = ivar_getName(ivar);
NSLog(@"%@",[NSString stringWithUTF8String:ivarName]);
}
输出: _name
也可以修改setter/getter和成员变量名,通过如下方法
@property (nonatomic, copy, setter=setMyClassName:, getter=myClassName) NSString *name;
@implementation MyClass
@synthesize name = _myClassName;
@end
通过制定setter/getter方法名,修改name成员变量需要使用@synthesize来制定成员变量名称。可以查方法和成员变量验证。
@synthesize 和 @dynamic
@synthesize 告诉编译器生成setter和getter方法 和成员变量(现在编译器默认自动生成setter/getter)。
@dynamic 是自己管理setter和getter方法 需要手动添加setter/getter方法, 当使用@dynamic修饰属性时,不生成成员变量(查询方法和成员变量,没有setter/getter和成员变量)。
@synthesize和@dynamic都是属性的implemented,不可以同时使用
当同时定义setter/getter不能使用成员变量
编译没有成员变量
解决办法使用@synthesize 告诉编译器生成一个成员变量。
@synthesize name = _name;
-(void)setName:(NSString *)name{
_name = name;
}
-(NSString *)name{
return _name;
}
property也可以在categroy中使用,这里有个容易混淆的概念就是在category中不能存在成员变量,但是可以使用属性。
在objc/runtime.h中可以看到categroy的结构体,其中没有存放成员变量的成员,所以在category中不存在成员变量
struct objc_category {
char * _Nonnull category_name OBJC2_UNAVAILABLE;
char * _Nonnull class_name OBJC2_UNAVAILABLE;
struct objc_method_list * _Nullable instance_methods OBJC2_UNAVAILABLE;
struct objc_method_list * _Nullable class_methods OBJC2_UNAVAILABLE;
struct objc_protocol_list * _Nullable protocols OBJC2_UNAVAILABLE;
}
因此只要在category中重写setter和getter编译器就不会生成成员变量。
个人知识点记录