分類(lèi)-Category
分類(lèi)的功能
在OC中,我們可以使用分類(lèi)為類(lèi)添加方法,屬性.也可以覆蓋類(lèi)原有的方法,自己添加新的實(shí)現(xiàn).(說(shuō)是覆蓋,其實(shí)不然.在稍后分類(lèi)加載時(shí)間會(huì)解釋原因)
分類(lèi)的結(jié)構(gòu)
const char *name;
classref_t cls;
WrappedPtr<method_list_t, PtrauthStrip> instanceMethods;
WrappedPtr<method_list_t, PtrauthStrip> classMethods;
struct protocol_list_t *protocols;
struct property_list_t *instanceProperties;
// Fields below this point are not always present on disk.
struct property_list_t *_classProperties;
method_list_t *methodsForMeta(bool isMeta) {
if (isMeta) return classMethods;
else return instanceMethods;
}
property_list_t *propertiesForMeta(bool isMeta, struct header_info *hi);
protocol_list_t *protocolsForMeta(bool isMeta) {
if (isMeta) return nullptr;
else return protocols;
}
};
從源碼可以看出,分類(lèi)是名為 category_t 的結(jié)構(gòu)體類(lèi)型數(shù)據(jù).
category_t的成員
- instanceMethods:實(shí)例方法
- classMethods:類(lèi)方法
- protocols:協(xié)議
- instanceProperties:實(shí)例屬性
- _classProperties:類(lèi)屬性
分類(lèi)的加載順序
分析iOS App啟動(dòng)時(shí)的一系列方法,可以看到分類(lèi)的加載規(guī)則.下面是一系列經(jīng)過(guò)的方法
_objc_init ==> map_images ==> map_images_nolock ==> _read_images ==> remethodizeClass ==> attachCategories
_read_images
// Discover classes. Fix up unresolved future classes. Mark bundle classes.
for (EACH_HEADER) {
if (! mustReadClasses(hi)) {
// Image is sufficiently optimized that we need not call readClass()
continue;
}
bool headerIsBundle = hi->isBundle();
bool headerIsPreoptimized = hi->isPreoptimized();
classref_t *classlist = _getObjc2ClassList(hi, &count);
for (i = 0; i < count; i++) {
Class cls = (Class)classlist[i];
Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized);
if (newCls != cls && newCls) {
// Class was moved but not deleted. Currently this occurs
// only when the new class resolved a future class.
// Non-lazily realize the class below.
resolvedFutureClasses = (Class *)
realloc(resolvedFutureClasses,
(resolvedFutureClassCount+1) * sizeof(Class));
resolvedFutureClasses[resolvedFutureClassCount++] = newCls;
}
}
}
// Discover protocols. Fix up protocol refs.
for (EACH_HEADER) {
extern objc_class OBJC_CLASS_$_Protocol;
Class cls = (Class)&OBJC_CLASS_$_Protocol;
assert(cls);
NXMapTable *protocol_map = protocols();
bool isPreoptimized = hi->isPreoptimized();
bool isBundle = hi->isBundle();
protocol_t **protolist = _getObjc2ProtocolList(hi, &count);
for (i = 0; i < count; i++) {
readProtocol(protolist[i], cls, protocol_map,
isPreoptimized, isBundle);
}
}
// Discover categories. Only do this after the initial category
// attachment has been done. For categories present at startup,
// discovery is deferred until the first load_images call after
// the call to _dyld_objc_notify_register completes. rdar://problem/53119145
if (didInitialAttachCategories) {
for (EACH_HEADER) {
load_categories_nolock(hi);
}
}
// Realize non-lazy classes (for +load methods and static instances)
for (EACH_HEADER) {
classref_t const *classlist = hi->nlclslist(&count);
for (i = 0; i < count; i++) {
Class cls = remapClass(classlist[i]);
if (!cls) continue;
addClassTableEntry(cls);
if (cls->isSwiftStable()) {
if (cls->swiftMetadataInitializer()) {
_objc_fatal("Swift class %s with a metadata initializer "
"is not allowed to be non-lazy",
cls->nameForLogging());
}
// fixme also disallow relocatable classes
// We can't disallow all Swift classes because of
// classes like Swift.__EmptyArrayStorage
}
realizeClassWithoutSwift(cls, nil);
}
}
從_read_images方法中,我摘抄了部分代碼.從這一部分代碼,我們可以看到類(lèi)的加載順序.
Discover classes. Fix up unresolved future classes. Mark bundle classes.
Discover protocols. Fix up protocol refs.
Discover categories.===> load_categories_nolock但是很明顯.這里有一個(gè)個(gè)判斷值didInitialAttachCategories.通過(guò)源碼看到.這個(gè)值一開(kāi)始為false.所以這時(shí)并未加載分類(lèi).
-
繼續(xù)往下走.會(huì)發(fā)現(xiàn)有一種情況.就是non-lazy classes會(huì)調(diào)用realizeClassWithoutSwift方法,方法內(nèi)部會(huì)調(diào)用methodizeClass在內(nèi)部使用objc::unattachedCategories.attachToClass 將分類(lèi)與類(lèi)連接上.
void
load_images(const char *path __unused, const struct mach_header *mh)
{
if (!didInitialAttachCategories && didCallDyldNotifyRegister) {
didInitialAttachCategories = true;
loadAllCategories();
}// Return without taking locks if there are no +load methods here. if (!hasLoadMethods((const headerType *)mh)) return; recursive_mutex_locker_t lock(loadMethodLock); // Discover load methods { mutex_locker_t lock2(runtimeLock); prepare_load_methods((const headerType *)mh); } // Call +load methods (without runtimeLock - re-entrant) call_load_methods();
}
static void loadAllCategories() {
mutex_locker_t lock(runtimeLock);for (auto *hi = FirstHeader; hi != NULL; hi = hi->getNext()) { load_categories_nolock(hi); }
}
load_categories_nolock
static void load_categories_nolock(header_info *hi) {
bool hasClassProperties = hi->info()->hasCategoryClassProperties();
size_t count;
auto processCatlist = [&](category_t * const *catlist) {
for (unsigned i = 0; i < count; i++) {
category_t *cat = catlist[i];
Class cls = remapClass(cat->cls);
locstamped_category_t lc{cat, hi};
// First, register the category with its target class.
// Then, rebuild the class's method lists (etc) if
// the class is realized.
if (cat->instanceMethods || cat->protocols
|| cat->instanceProperties)
{
if (cls->isRealized()) {
attachCategories(cls, &lc, 1, ATTACH_EXISTING);
} else {
objc::unattachedCategories.addForClass(lc, cls);
}
}
if (cat->classMethods || cat->protocols
|| (hasClassProperties && cat->_classProperties))
{
if (cls->ISA()->isRealized()) {
attachCategories(cls->ISA(), &lc, 1, ATTACH_EXISTING | ATTACH_METACLASS);
} else {
objc::unattachedCategories.addForClass(lc, cls->ISA());
}
}
}
};
processCatlist(_getObjc2CategoryList(hi, &count));
processCatlist(_getObjc2CategoryList2(hi, &count));
}
從load_categories_nolock方法中摘抄了部分代碼,發(fā)現(xiàn)內(nèi)部調(diào)用了attachCategories.
attachCategories
// Attach method lists and properties and protocols from categories to a class.
// Assumes the categories in cats are all loaded and sorted by load order,
// oldest categories first.
static void
attachCategories(Class cls, const locstamped_category_t *cats_list, uint32_t cats_count,
int flags)
{
if (slowpath(PrintReplacedMethods)) {
printReplacements(cls, cats_list, cats_count);
}
if (slowpath(PrintConnecting)) {
_objc_inform("CLASS: attaching %d categories to%s class '%s'%s",
cats_count, (flags & ATTACH_EXISTING) ? " existing" : "",
cls->nameForLogging(), (flags & ATTACH_METACLASS) ? " (meta)" : "");
}
/*
* Only a few classes have more than 64 categories during launch.
* This uses a little stack, and avoids malloc.
*
* Categories must be added in the proper order, which is back
* to front. To do that with the chunking, we iterate cats_list
* from front to back, build up the local buffers backwards,
* and call attachLists on the chunks. attachLists prepends the
* lists, so the final result is in the expected order.
*/
constexpr uint32_t ATTACH_BUFSIZ = 64;
method_list_t *mlists[ATTACH_BUFSIZ];
property_list_t *proplists[ATTACH_BUFSIZ];
protocol_list_t *protolists[ATTACH_BUFSIZ];
uint32_t mcount = 0;
uint32_t propcount = 0;
uint32_t protocount = 0;
bool fromBundle = NO;
bool isMeta = (flags & ATTACH_METACLASS);
auto rwe = cls->data()->extAllocIfNeeded();
for (uint32_t i = 0; i < cats_count; i++) {
auto& entry = cats_list[i];
method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
if (mlist) {
if (mcount == ATTACH_BUFSIZ) {
prepareMethodLists(cls, mlists, mcount, NO, fromBundle, __func__);
rwe->methods.attachLists(mlists, mcount);
mcount = 0;
}
mlists[ATTACH_BUFSIZ - ++mcount] = mlist;
fromBundle |= entry.hi->isBundle();
}
property_list_t *proplist =
entry.cat->propertiesForMeta(isMeta, entry.hi);
if (proplist) {
if (propcount == ATTACH_BUFSIZ) {
rwe->properties.attachLists(proplists, propcount);
propcount = 0;
}
proplists[ATTACH_BUFSIZ - ++propcount] = proplist;
}
protocol_list_t *protolist = entry.cat->protocolsForMeta(isMeta);
if (protolist) {
if (protocount == ATTACH_BUFSIZ) {
rwe->protocols.attachLists(protolists, protocount);
protocount = 0;
}
protolists[ATTACH_BUFSIZ - ++protocount] = protolist;
}
}
if (mcount > 0) {
prepareMethodLists(cls, mlists + ATTACH_BUFSIZ - mcount, mcount,
NO, fromBundle, __func__);
rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);
if (flags & ATTACH_EXISTING) {
flushCaches(cls, __func__, [](Class c){
// constant caches have been dealt with in prepareMethodLists
// if the class still is constant here, it's fine to keep
return !c->cache.isConstantOptimizedCache();
});
}
}
rwe->properties.attachLists(proplists + ATTACH_BUFSIZ - propcount, propcount);
rwe->protocols.attachLists(protolists + ATTACH_BUFSIZ - protocount, protocount);
}
- method_list_t *mlists(方法數(shù)組)
- property_list_t *proplists(屬性數(shù)組)
- protocol_list_t *protolists(協(xié)議數(shù)組)
可以看到.在attachCategories方法中.會(huì)加載方法,屬性,協(xié)議.并且.從load_categories_nolock方法中可以看出.先加載實(shí)例方法,再加載類(lèi)方法.也就是說(shuō).是先處理類(lèi)對(duì)象,再處理元類(lèi)對(duì)象.
在attachCategories 中遍歷加載的分類(lèi)列表.將每一個(gè)分類(lèi)中方法,屬性,協(xié)議通過(guò)attachLists方法.將三個(gè)數(shù)組拼接到類(lèi)對(duì)象或者元類(lèi)對(duì)象的對(duì)應(yīng)的 方法,屬性,協(xié)議 列表中.
從attachToClass看分類(lèi)加載時(shí)機(jī)
從源碼可以看出.加載分類(lèi)的時(shí)候.都會(huì)調(diào)用objc::unattachedCategories.attachToClass.我添加了自己的Test類(lèi)做比較.在attachToClass中增加了自己的代碼并添加斷點(diǎn).查看調(diào)用棧
1.Test類(lèi)與分類(lèi)皆實(shí)現(xiàn)了+load方法
2.Test類(lèi)實(shí)現(xiàn)+load方法,Test的分類(lèi)沒(méi)有實(shí)現(xiàn)+load方法
3.Test類(lèi)沒(méi)有實(shí)現(xiàn)+load方法,Test的分類(lèi)實(shí)現(xiàn)+load方法
4.Test類(lèi)沒(méi)實(shí)現(xiàn)+load方法,Test的分類(lèi)也沒(méi)有實(shí)現(xiàn)+load方法
可以看出.只要一個(gè)類(lèi)實(shí)現(xiàn)了+load的方法.類(lèi)就會(huì)強(qiáng)制在read_images時(shí)進(jìn)行分類(lèi)加載.
而類(lèi)不實(shí)現(xiàn)+load,分類(lèi)實(shí)現(xiàn)了,則會(huì)在load_images方法進(jìn)行分類(lèi)加載
而類(lèi)與分類(lèi)都不實(shí)現(xiàn)的情況下.則會(huì)在調(diào)用方法時(shí),進(jìn)行類(lèi)的加載.msgSend ===> lookUpImpOrForward
attachLists
void attachLists(List* const * addedLists, uint32_t addedCount) {
if (addedCount == 0) return;
if (hasArray()) {
// many lists -> many lists
uint32_t oldCount = array()->count;
uint32_t newCount = oldCount + addedCount;
array_t *newArray = (array_t *)malloc(array_t::byteSize(newCount));
newArray->count = newCount;
array()->count = newCount;
for (int i = oldCount - 1; i >= 0; i--)
newArray->lists[i + addedCount] = array()->lists[i];
for (unsigned i = 0; i < addedCount; i++)
newArray->lists[i] = addedLists[i];
free(array());
setArray(newArray);
validate();
}
else if (!list && addedCount == 1) {
// 0 lists -> 1 list
list = addedLists[0];
validate();
}
else {
// 1 list -> many lists
Ptr<List> oldList = list;
uint32_t oldCount = oldList ? 1 : 0;
uint32_t newCount = oldCount + addedCount;
setArray((array_t *)malloc(array_t::byteSize(newCount)));
array()->count = newCount;
if (oldList) array()->lists[addedCount] = oldList;
for (unsigned i = 0; i < addedCount; i++)
array()->lists[i] = addedLists[i];
validate();
}
}
從attachLists中可以看出.在擴(kuò)容方法數(shù)組時(shí),會(huì)將類(lèi)的舊方法往后移,然后通過(guò)for循環(huán)將分類(lèi)的方法填充進(jìn)空出的位置中.所以,如果分類(lèi)有跟本類(lèi)同名方法,并不會(huì)覆蓋原有方法.只是分類(lèi)方法在方法列表中排前,所以msgSend過(guò)程中.會(huì)先被命中.
并且多個(gè)分類(lèi)有同名方法時(shí),加載順序是怎么樣呢?
@interface Test : NSObject
@end
@implementation Test
@end
@interface Test (Test1)
+ (void)test;
@end
@implementation Test (Test1)
+ (void)test {
NSLog(@"%s",__func__);
}
@end
@interface Test (Test2)
+ (void)test;
@end
@implementation Test (Test2)
+ (void)test {
NSLog(@"%s",__func__);
}
@end
build phases中,在調(diào)換Test1,Test2的順序后.打印出的結(jié)果也不痛.
//當(dāng)Test1在上
TestExtension[60879:1094130] +[Test(Test2) test]
//Test2在上
TestExtension[60935:1095749] +[Test(Test1) test]
分類(lèi)添加屬性
上面看到.雖然category_t中有屬性列表,并無(wú)成員列表.
所以為類(lèi)添加屬性后,由于不存在成員列表.所以也不會(huì)像類(lèi)聲明屬性時(shí),默認(rèn)會(huì)有@synthesize xxxx這一步驟.生成getter,setter方法和成員名成員標(biāo)量.
所以當(dāng)我們直接使用分類(lèi)聲明的屬性時(shí),無(wú)論是取值還是賦值.都會(huì)報(bào)對(duì)應(yīng)的 unrecognized selector sent to instance錯(cuò)誤.
那么,我們想要通過(guò)分類(lèi),為類(lèi)添加屬性,應(yīng)該怎么做呢?
我們可以通過(guò)OC的關(guān)聯(lián)對(duì)象來(lái)完成分類(lèi)為類(lèi)添加屬性的功能.
關(guān)聯(lián)對(duì)象
runtime中,關(guān)聯(lián)對(duì)象允許我們動(dòng)態(tài)的把一個(gè)對(duì)象與某一塊地址動(dòng)態(tài)的關(guān)聯(lián)起來(lái).篇幅太長(zhǎng),這里不做原理的分析.只簡(jiǎn)單寫(xiě)一下怎么完成關(guān)聯(lián)對(duì)象
//Test+Test1.h
#import "Test.h"
NS_ASSUME_NONNULL_BEGIN
@interface Test (Test1)
@property(nonatomic, copy)NSString *testName;
@end
NS_ASSUME_NONNULL_END
//Test+Test1.m
#import "Test+Test1.h"
#import <objc/runtime.h>
@implementation Test (Test1)
- (void)setTestName:(NSString *)testName {
objc_setAssociatedObject(self, "testName", testName, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)testName {
return objc_getAssociatedObject(self, "testName");
}
@end
上述就是使用關(guān)聯(lián)對(duì)象,完成分類(lèi)為類(lèi)添加屬性的示例.