1.成员变量和属性的概念
成员变量(实例变量)是类私有的,不可以通过点语法来访问(说是私有的,其实外部可以通过kvc访问,所以oc中不存在真正的私有)
属性就是@property修饰的,格式:
@interface third : NSObject {
NSString *a;
}
@property(strong,atomic) NSString *b;
-(void)pp;
-(NSString*)setA:(NSString*)value;
@end
@implementation third
-(id)init{
self = [super init];
self.b = @"123";
return self;
}
-(void)pp{
self.b = @"pp";
_b = @"oo";
NSLog(@"%@",self.b);
}
-(void)set
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
third *f = [[third alloc] init];
[f setValue:@"77" forKey:@"b"];
NSLog(@"%@",f.b);
NSLog(@"%@",[f valueForKey:@"b"]);
}
return 0;
}
a就是成员变量,b就是属性,b可以通过点语法访问,a可以用kvc
被@property修饰的属性,会自动创建带_的成员变量,例如上面就会自动创建_b的成员变量,在third类内部,_b和self.b是一样的,但是外部莫的_b。
所以说kvc这个玩意功能挺强大,他可以修改系统不能修改的东西,使代码更加灵活,同时也是把双刃剑。
2.category分类,也就是扩展
分类里面只能创建方法和属性,不能创建成员变量。
其底层是一个结构体,如下:从category的定义也可以看出category的可为(可以添加实例方法,类方法,甚至可以实现协议,添加属性)和不可为(无法添加实例变量)
struct category_t {
const char *name; // 类名
classref_t cls; // 类
struct method_list_t *instanceMethods; // 实例方法列表
struct method_list_t *classMethods; // 类方法列表
struct protocol_list_t *protocols; // 协议列表
struct property_list_t *instanceProperties; // 属性列表
// Fields below this point are not always present on disk.
struct property_list_t *_classProperties;
// 如果是元类,就返回类方法列表;否则返回实例方法列表
method_list_t *methodsForMeta(bool isMeta) {
if (isMeta) return classMethods;
else return instanceMethods;
}
property_list_t *propertiesForMeta(bool isMeta, struct header_info *hi);
};
作者:哈哈哈哈哈你是逗比吗
链接:https://juejin.cn/post/6904917975086661640
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。