一個面試題:問alloc和allocWithZone是什么?有啥子區(qū)別埂息?
+ (instancetype)allocWithZone:(struct _NSZone *)zone
+ (instancetype)alloc
(以下是我自己看了少部分資料自己意淫想象疑俭,不算嚴(yán)謹(jǐn)?shù)恼_觀點,慎讀伍玖。)
首先alloc和allocWithZone都是創(chuàng)建一個對象實例
使用alloc方法創(chuàng)建一個類的實例的時候嫩痰,其實最后還是會調(diào)用 allocWithZone 方法。在OC中allocWithZone這個方法應(yīng)該是棄用了的窍箍,只是由于歷史原因蘋果還保留著這個函數(shù)串纺。
這個NSZone是個什么東西呢
據(jù)史料記載,NSZone是用來分配和管理一段內(nèi)存空間的一個結(jié)構(gòu)體椰棘。
然后我們查看NSZone的頭文件發(fā)現(xiàn)以下幾個函數(shù)
FOUNDATION_EXPORT NSZone *NSCreateZone(NSUInteger startSize, NSUInteger granularity, BOOL canFree) NS_SWIFT_UNAVAILABLE("Zone-based memory management is unavailable");
FOUNDATION_EXPORT NSString *NSZoneName(NSZone * __nullable zone) NS_SWIFT_UNAVAILABLE("Zone-based memory management is unavailable");
FOUNDATION_EXPORT NSZone * __nullable NSZoneFromPointer(void *ptr) NS_SWIFT_UNAVAILABLE("Zone-based memory management is unavailable");
FOUNDATION_EXPORT void *NSZoneMalloc(NSZone * __nullable zone, NSUInteger size) NS_SWIFT_UNAVAILABLE("Zone-based memory management is unavailable");
FOUNDATION_EXPORT void *NSZoneCalloc(NSZone * __nullable zone, NSUInteger numElems, NSUInteger byteSize) NS_SWIFT_UNAVAILABLE("Zone-based memory management is unavailable");
FOUNDATION_EXPORT void *NSZoneRealloc(NSZone * __nullable zone, void * __nullable ptr, NSUInteger size) NS_SWIFT_UNAVAILABLE("Zone-based memory management is unavailable");
FOUNDATION_EXPORT void NSZoneFree(NSZone * __nullable zone, void *ptr) NS_SWIFT_UNAVAILABLE("Zone-based memory management is unavailable");
看起來跟C語言的malloc,calloc,free等函數(shù)相似纺棺,所以大概NSZone就是可以分配一段連續(xù)空間。你可以將你創(chuàng)建的類實例都存在這個空間邪狞,自己管理祷蝌。
比如你都用allocWithZone創(chuàng)建三個NSDictionary ,那這三個字典肯定是連在一起存儲的。然后你連著讀取三字典的數(shù)據(jù)帆卓,地址相鄰理論上讀取速度更快巨朦。
反正當(dāng)年肯定用這個有好處米丘,現(xiàn)在蘋果都幫你處理好了,不用管了糊啡,官方也不建議再用這個接口了拄查。
那么最后答案就是:
alloc和allocWithZone都是創(chuàng)建一個類實例的方法
不同之處在于,alloc無法指定一個NSZone來存儲自己創(chuàng)建的實例悔橄,它最終調(diào)用的是allocWithZone(nil)靶累,使用的是系統(tǒng)給定的NSZone
allocWithZone可以指定自己的NSZone來存儲自己創(chuàng)建的實例,如果zone傳nil 它使用的就是系統(tǒng)給定的NSZone