category 作用
- 聲明私有方法
- 分解體積旁大的類文件
- 把framework的私有方法公開
特點(diǎn)
編譯時(shí)編譯分類代碼,但是到運(yùn)行時(shí)才把分類方法屬性協(xié)議代理等添加到宿主類
- 分類添加的方法可以"覆蓋"原類方法
- 同名類方法誰(shuí)能生效取決于編譯順序
- 名字相同的分類會(huì)引起編譯報(bào)錯(cuò)。
可以添加哪些內(nèi)容
- 實(shí)例方法
- 類方法
- 協(xié)議
- 屬性:只是添加了get和set方法,并沒(méi)有添加_property成員變量
category結(jié)構(gòu)體
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 *instanceMethods;
method_list_t *methodsForMeta(bool isMeta){
if(isMeta) return classMethods;
else return instanceMethods;
}
property_list_t *propertiesForMeta_(bool isMeta){
if(isMeta)return nil;
else return instanceProperties;
}
}
擴(kuò)展(Extension)
- 編譯時(shí)決議
- 只以聲明的形式存在,多數(shù)情況下寄生于宿主類的m文件
- 不能為系統(tǒng)類添加擴(kuò)展
代理(Delegate)
- 一種軟件設(shè)計(jì)模式
- iOS當(dāng)中以@protocol形式表現(xiàn)
- 傳遞方式一對(duì)一
通知(NSNotification)
通知者發(fā)生消息,經(jīng)由通知中心向多個(gè)接收者發(fā)送消息
- 使用觀察者模式來(lái)實(shí)現(xiàn)的用于跨層傳遞消息的機(jī)制
- 傳遞方式一對(duì)多
內(nèi)部大致有個(gè)map,以通知名為key,所有的觀察者列表為value。
KVO(key-value-observing)
KVO是Objective-C對(duì)觀察者設(shè)計(jì)模式的又一實(shí)現(xiàn)。
Apple使用了isa混寫(isa-swizzling)來(lái)實(shí)現(xiàn)KVO
當(dāng)調(diào)用addObserver方法后,系統(tǒng)會(huì)在運(yùn)行時(shí)動(dòng)態(tài)創(chuàng)建NSKVONotifying_A這么個(gè)類,將原來(lái)的類的isa指針指向這個(gè)類,通過(guò)重這個(gè)類的set方法實(shí)現(xiàn)通知觀察者
- (void)setValue:(id)obj
{
[self willChangeValueForKey:@"KeyPath"];
[super setValue:obj];
[self didChangeValueForKey:@"KeyPath"];
}
我們手動(dòng)調(diào)用[self willChangeValueForKey:@"KeyPath"];[self didChangeValueForKey:@"KeyPath"];這兩個(gè)方法也能達(dá)到調(diào)用監(jiān)聽回調(diào)的方法。