屬性-Property

1 和Java的成員變量的區(qū)別

Java的成員變量在編譯器就已經(jīng)確定。OC在運(yùn)行期,可以動(dòng)態(tài)添加成員變量。

2 Property的作用

1 剛開始只是在.h文件聲明getter和setter方法;
2 WWDC2012,可以在.h文件聲明getter和setter方法;在.m文件創(chuàng)建帶下劃線成員變量,實(shí)現(xiàn)getter和setter方法

3 Property的關(guān)鍵字

1 原子性

  • nonatomic
  • atomic

2 讀寫權(quán)限

  • readwrite
  • readonly

3 內(nèi)存管理

  • assign
  • strong
  • weak
  • copy
  • unsafe_unretained

4 方法名

  • getter
  • setter

默認(rèn)關(guān)鍵字是什么

  • 基本數(shù)據(jù)類型:atomic,readwrite,assign
  • 對象:atomic,readwrite,strong

4 weak和assign的區(qū)別

  • weak用于對象;assign用于基本數(shù)據(jù)類型
  • weak會(huì)自動(dòng)置nil

5 copy的用法

  • 一般用于NSString,NSDictionary,NSArray。保證屬性指向的是不可變對象
  • 也用于Block,沿習(xí)MRC的傳統(tǒng);實(shí)際ARC下,Block一般會(huì)被自動(dòng)拷貝到堆

6 weak變量是如何置nil

系統(tǒng)將weak變量指向的對象的地址和weak變量放到一個(gè)hash表中,以weak變量指向?qū)ο蟮膬?nèi)存地址為key,weak變量是value。當(dāng)weak變量指向?qū)ο蟊讳N毀之前,系統(tǒng)會(huì)通過其內(nèi)存地址,找到weak變量,并將其置為nil

7 Property的實(shí)質(zhì)

Property的本質(zhì)就是:成員變量 + setter + getter,包含5部分:

  1. OBJC_IVAR_$類名_$屬性名稱:該屬性的偏移量是在編譯時(shí)決定
  2. ivar_list:成員變量列表
  3. prop_list: 屬性列表
  4. method_list:方法列表
  5. setter和getter方法對應(yīng)的實(shí)現(xiàn)

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;
  • 分類的結(jié)構(gòu)體沒有包含成員變量列表
  • 分類結(jié)構(gòu)體為什么這樣設(shè)計(jì):類的成員變量是按照偏移量確定,如果基類動(dòng)態(tài)成員變量,就會(huì)破壞成員變量布局;
  • 屬性本身是可以添加到類的prop_list;
  • 方法是在運(yùn)行時(shí)動(dòng)態(tài)找的,所以可以動(dòng)態(tài)添加方法

9 運(yùn)行時(shí)創(chuàng)建的類,能夠增加成員變量嗎?

  • 可以通過class_addIvar函數(shù)添加
  • 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.lxweimin.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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容