單例模式,重用UITableViewCell,代碼片段庫

單例模式:
1.設置一個全局靜態變量來保存單例對象。
2.覆寫一些方法來阻止創建多個對象,使被設爲單例的那個類始終只有一個對象。
代碼:
#import "PossessionStore.h"
#import "Possession.h"

static PossessionStore *defaultStore = nil;

@implementation PossessionStore 


+ (PossessionStore *)defaultStore
{
    if (!defaultStore) {
        //創建唯一的實例
        defaultStore = [[super allocWithZone:NULL] init];
    }
    return defaultStore;
}

//阻止增加一個實例
+ (id)allocWithZone:(NSZone *)zone
{
    return [self defaultStore];
}

- (id)init
{
    if (defaultStore) {
        return defaultStore;
    }
    
    self = [super init];
    if (self) {
        allPossessions = [[NSMutableArray alloc] init];
    }
    return self;
}


- (id)retain{
    return self;
}

- (oneway void)release {

}

- (NSUInteger)retainCount {
    return NSUIntegerMax;
}

3.爲什麼只覆蓋+ (id)allocWithZone:(NSZone *)zone而沒有覆蓋alloc呢?如果調用了alloc豈不是會分配內存而導致內存被佔用。官網給出的解釋:

The isa instance variable of the new instance is initialized to a data structure that describes the class; memory for all other instance variables is set to 0. You must use an init... method to complete the initialization process。

Do not override alloc to include initialization code. Instead, implement class-specific versions of init... methods. For historical reasons, alloc invokes allocWithZone:.(歷史原因,alloc會調用allocWithZone:)

重用UITableViewCell

1.當用戶滾動表格時,部分UITableViewCell對象會移出窗口,UITableView對象會窗口外的UITableViewCell對象放入UITableViewCell對象池,等待重用。

2.當UITableView對象要求數據源(dataSource)返回UITableViewCell對象時,數據源會先查看這個對象池,如果有未使用的UITableViewCell對象,數據源會用新的數據配置這個UITableViewCell對象,然後返回給UITableVIew,從而避免創建對象。代碼如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //先查看這個對象池,如果存在,則利用這個cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"] autorelease];
    }

    Possession *possession = [[[PossessionStore defaultStore] allPossessions] objectAtIndex:[indexPath row]];
    [[cell textLabel] setText:[possession description]];
    return cell;
}

3.在創建UITableViewCell時,指定reuseIdentifier,這樣在UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];中就能根據相應的reuseIdentifier去查找相應的UITableViewCell。
代碼片段庫

1.當你輸入init,然後enter,代碼會自動補全,這就是代碼來自代碼片段庫,如下圖


雙擊後出現


2.Completion Shortcut表示要在文件中鍵入的字符,鍵入這個字符後,點擊enter鍵就會自動補全了。

3.官方給出的是不能進行修改的,但是自己可以創建新的並可以修改,選中要寫入的代碼(雙擊選中),再拖到上面第一個圖所示的框就會創建一個新的了,然後自己在裏面添加,修改,值得一提的是在代碼中加上#words#就可以把裏面的words定義爲佔位符並處於選中狀態。如#initializations#就會得到上面圖片中的initializations所處的效果。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章