单例模式,重用UITableViewCell,代码片段库

来源:互联网 发布:淘宝的快递为什么便宜 编辑:程序博客网 时间:2024/05/17 21:58
单例模式:
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所处的效果。

0 0
原创粉丝点击