OC学习笔记-iVar和property

385 阅读1分钟

描述


在OC Class中声明变量,通常使用以下两种方式。

- @property
@interface Person : NSObject
@property(nonatomic, strong) NSString *name;
@end;
- Instance variable(iVar)
@interface Person : NSObject{
    NSString *_name;
}
@end

那么,这两种方式的区别在哪呢?

差异

  • private vs public(访问权限)

    对于类型为 private/protected 的变量,使用iVar;对于类型为 public 的变量,使用property。

    如果想在使用private类型变量的同时享有property属性所提供的特性如strong、nonatomic等,可以在implementation文件中声明property作为private的property;

    对于iVar, 可以使用@private、@protected和@public来限制访问权限。但这些只能限制其子类的访问,对于实例的访问无法施加影响。更详细的阐释可点击这里

  • usage(使用)

    在类中可以直接使用iVar,如 _name;对于property在类中需要使用self来进行调用,如self.name

    此外,property在声明时会生成对应的getter和setter方法,在新版本的XCode中还会生成使用方法与iVar相同的变量,若同时重写了property的setter和getter方法,这种变量需重新利用@synthesize对变量进行声明才可以继续使用。如@synthesize name = _name;

    synthesize仅供property使用,有关synthesize的详细用法不在这里展开。

Reference


hongchaozhang.github.io/blog/2015/0…