属性-Property

1 和Java的成员变量的区别

Java的成员变量在编译器就已经确定。OC在运行期,可以动态添加成员变量。

2 Property的作用

1 刚开始只是在.h文件声明getter和setter方法;
2 WWDC2012,可以在.h文件声明getter和setter方法;在.m文件创建带下划线成员变量,实现getter和setter方法

3 Property的关键字

1 原子性

  • nonatomic
  • atomic

2 读写权限

  • readwrite
  • readonly

3 内存管理

  • assign
  • strong
  • weak
  • copy
  • unsafe_unretained

4 方法名

  • getter
  • setter

默认关键字是什么

  • 基本数据类型:atomic,readwrite,assign
  • 对象:atomic,readwrite,strong

4 weak和assign的区别

  • weak用于对象;assign用于基本数据类型
  • weak会自动置nil

5 copy的用法

  • 一般用于NSString,NSDictionary,NSArray。保证属性指向的是不可变对象
  • 也用于Block,沿习MRC的传统;实际ARC下,Block一般会被自动拷贝到堆

6 weak变量是如何置nil

系统将weak变量指向的对象的地址和weak变量放到一个hash表中,以weak变量指向对象的内存地址为key,weak变量是value。当weak变量指向对象被销毁之前,系统会通过其内存地址,找到weak变量,并将其置为nil

7 Property的实质

Property的本质就是:成员变量 + setter + getter,包含5部分:

  1. OBJC_IVAR_$类名_$属性名称:该属性的偏移量是在编译时决定
  2. ivar_list:成员变量列表
  3. prop_list: 属性列表
  4. method_list:方法列表
  5. setter和getter方法对应的实现

8 为什么在分类中不能添加成员变量;

typedef 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;
} category_t;
  • 分类的结构体没有包含成员变量列表
  • 分类结构体为什么这样设计:类的成员变量是按照偏移量确定,如果基类动态成员变量,就会破坏成员变量布局;
  • 属性本身是可以添加到类的prop_list;
  • 方法是在运行时动态找的,所以可以动态添加方法

9 运行时创建的类,能够增加成员变量吗?

  • 可以通过class_addIvar函数添加
  • This function may only be called after objc_allocateClassPair(::_:)
    and before objc_registerClassPair(_:)
    . Adding an instance variable to an existing class is not supported.
    The class must not be a metaclass. Adding an instance variable to a metaclass is not supported.

参考文章

8和9的

http://tech.meituan.com/DiveIntoCategory.html
http://quotation.github.io/objc/2015/05/21/objc-runtime-ivar-access.html
http://www.jianshu.com/p/935142af6a47
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011210-CH1-SW1
https://developer.apple.com/library/content/documentation/General/Conceptual/DevPedia-CocoaCore/DynamicBinding.html#//apple_ref/doc/uid/TP40008195-CH15-SW1

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容