• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

oc复习啦一kvc和属性,成员变量

武飞扬头像
真的没有名字取了
帮助1

1.成员变量和属性的概念

成员变量(实例变量)是类私有的,不可以通过点语法来访问(说是私有的,其实外部可以通过kvc访问,所以oc中不存在真正的私有)

属性就是@property修饰的,格式:

  1.  
    @interface third : NSObject {
  2.  
    NSString *a;
  3.  
    }
  4.  
     
  5.  
    @property(strong,atomic) NSString *b;
  6.  
     
  7.  
    -(void)pp;
  8.  
    -(NSString*)setA:(NSString*)value;
  9.  
     
  10.  
    @end
  11.  
     
  12.  
     
  13.  
    @implementation third
  14.  
     
  15.  
    -(id)init{
  16.  
    self = [super init];
  17.  
    self.b = @"123";
  18.  
    return self;
  19.  
    }
  20.  
     
  21.  
    -(void)pp{
  22.  
    self.b = @"pp";
  23.  
    _b = @"oo";
  24.  
    NSLog(@"%@",self.b);
  25.  
    }
  26.  
     
  27.  
    -(void)set
  28.  
     
  29.  
    @end
  30.  
     
  31.  
     
  32.  
    int main(int argc, const char * argv[]) {
  33.  
    @autoreleasepool {
  34.  
    third *f = [[third alloc] init];
  35.  
    [f setValue:@"77" forKey:@"b"];
  36.  
    NSLog(@"%@",f.b);
  37.  
    NSLog(@"%@",[f valueForKey:@"b"]);
  38.  
    }
  39.  
    return 0;
  40.  
    }

a就是成员变量,b就是属性,b可以通过点语法访问,a可以用kvc

被@property修饰的属性,会自动创建带_的成员变量,例如上面就会自动创建_b的成员变量,在third类内部,_b和self.b是一样的,但是外部莫的_b。

所以说kvc这个玩意功能挺强大,他可以修改系统不能修改的东西,使代码更加灵活,同时也是把双刃剑。

2.category分类,也就是扩展

分类里面只能创建方法和属性,不能创建成员变量。

其底层是一个结构体,如下:从category的定义也可以看出category的可为(可以添加实例方法,类方法,甚至可以实现协议,添加属性)和不可为(无法添加实例变量)

  1.  
    struct category_t {
  2.  
    const char *name; // 类名
  3.  
    classref_t cls; //
  4.  
    struct method_list_t *instanceMethods; // 实例方法列表
  5.  
    struct method_list_t *classMethods; // 类方法列表
  6.  
    struct protocol_list_t *protocols; // 协议列表
  7.  
    struct property_list_t *instanceProperties; // 属性列表
  8.  
    // Fields below this point are not always present on disk.
  9.  
    struct property_list_t *_classProperties;
  10.  
    // 如果是元类,就返回类方法列表;否则返回实例方法列表
  11.  
    method_list_t *methodsForMeta(bool isMeta) {
  12.  
    if (isMeta) return classMethods;
  13.  
    else return instanceMethods;
  14.  
    }
  15.  
     
  16.  
    property_list_t *propertiesForMeta(bool isMeta, struct header_info *hi);
  17.  
    };
  18.  
     
  19.  
    作者:哈哈哈哈哈你是逗比吗
  20.  
    链接:https://juejin.cn/post/6904917975086661640
  21.  
    来源:稀土掘金
  22.  
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgabbgc
系列文章
更多 icon
同类精品
更多 icon
继续加载