類簇(class cluster)是一種設計模式,在foundation framework中被廣泛使用,舉個簡單的例子
nsarray *arr = [nsarray arraywithobjects:@顯然__nsarrayi是乙個私有類,來看看這個類的標頭檔案"foo"
,@"bar"
, nil];
nslog(@"arr class:%@"
, [arr
class
]);
// output: __nsarrayi
@可以看出__nsarrayi繼承了nsarray。為什麼要這麼設計呢?拿nsnumber來舉個例子,我們都知道nsnumber可以儲存多種型別的數字,如int/float/double等等,一種方式是把nsnumber作為基類,然後分別去實現各自的子類,像這樣:inte***ce
__nsarrayi : nsarray
//...
初看起來也沒什麼問題,但如果子類很多,像這樣:
這對使用者來說顯然不夠方便,得記住這麼多類。如果使用類簇,問題就變得簡單了,把number作為抽象基類,子類各自實現訪問方式,然後在基類中定義多個初始化方式,像這樣:
現在只需要記住乙個類就可以了。nsnumber的初始化偽**大概像這樣:
- (id)initwithbool在ios專案中的應用- (id)initwithlong
//...
@implementation hbwate***llviewcontroller使用起來類似這樣[[hbwate***llviewcontroller alloc]initwithboardid:9527] 或 [[hbwate***llviewcontroller alloc]initwithliked]。如果有新的datasource,新加乙個初始化方法即可,對於使用者來說,開啟標頭檔案,看下init開頭的方法就行了。- (id)initwithliked
- (id)initwithboardid:(nsinteger)boardid
#pragma mark - 通用的方法
- (psuicollectionviewcell *)collectionview:(psuicollectionview *)collectionview
cellforitematindexpath:(nsindexpath *)indexpath
// ...
#pragma mark - 每個子類需要實現的方法
- (void
)fetchmoredata
再舉個例子,現在很多應用需要同時兼顧ios6和ios7,在表現上需要為不同的系統載入不同的資源,最簡單粗暴的方法就是各種if/else判斷,像這樣:
if不夠優雅,可以使用類簇的思想來去掉if/else判斷,把跟檢視具體元素無關的**放在基類,跟系統版本相關的**拆成兩個子類,然後在各自的類中載入相應的資源。([[uidevice currentdevice]systemmajorversion]
else
/* testview.h */這裡alloc時並沒有返回testview類,而是根據系統版本返回testviewios6 或 testviewios7。@inte***ce
testview: uiview
/* common method */
- ( void
)test;
@end
/* testview.m */
@implementation testview
+ (id)alloc
else }
else }
- ( void
)test
{} @end
/* testviewios6.m */小結@implementation testviewios6: testview
- (void
)drawrect: (cgrect)rect
@end
/* testviewios7.m */
@implementation testviewios7
- (void
)drawrect: (cgrect)rect
@end
類簇的本質其實是抽象工廠,類簇也可以有多個基類,如nsarray, nsmutablearray, 後者就是繼承的前者。它對一些「大同小異」的問題,往往會有不錯的效果。
轉至
OC中的類簇的使用和初始化方法中屬性的使用
今天遇到了幾個和字串相關的記憶體問題,和大家分享一下 nsstring name nsstring alloc initwithstring 張三 nslog d name retaincount 這兩行 的列印結果是 1,nsstring astring nsstring alloc initwi...
OC學習筆記 OC中的類
1.objc跟c的區別與聯絡 首先 objc是乙個物件導向的語言 封裝 繼承 多型 objc相當於c的乙個超集 即objc允許使用任何c語言 但增加了許多c沒有的特點 bigger easier 2.objc中的類與物件 類由介面 xx.h inte ce 和實現 xx.m implementati...
類簇的設計
這兒為了驗證xcode上類簇nsnumber實現過程設計了乙個簡化版類簇lonumber import inte ce lonumber nsobject property readonly int intvalue 獲取物件對應的 int資料 property readonly bool bool...