Auto-Release

如果我们今天有一个method,会返回一个Objective-C 实例,假使写成这样:

- (NSNumber *)one
{
    return [[NSNumber alloc] initWithInt:1];
}

那么,每次用到了由one 这个method产生出来的实例,用完之后,都需要记住要release这个实例,很容易造成疏忽。习惯上,我们会让这个method 回传auto-release的实例。像是写成这样:

- (NSNumber *)one
{
    return [[[NSNumber alloc] initWithInt:1] autorelease];
}

所谓的auto-release 其实也没有多么自动,而是说,在这一轮run loop中我们先不释放这个实例,让这个实例可以在这一轮run loop 中都可以使用,但是先打上一个标签,到了下一轮run loop 开始时,让runtime 判断有哪些前一轮runloop 中被标成是auto-release 的实例,这个时候才减少retain count 决定是否要释放物件。

我们在这边遇到了一个陌生的名词: run loop,我们会在Responder这一章当中说明。

在建立Foundation物件的时候,除了可以调用allocinit以及new之外(new这个method其实就相当于呼叫了allocinit;比方说,我们呼叫[NSObject new],就等同于呼叫了[[NSObject alloc] init]。),还可以调用另外一组与实例名称相同的method。

NSString为例,有一个叫做initWithString的instance method,就有一个对应的class method叫做stringWithFormat,使用这一组method,就会产生auto-release的物件。也就是说,呼叫了[NSString stringWithFormat:...],相当于调用了[[[NSString alloc] initWithFormat:...] autorelease]。使用这一组method,可以让代码较为精简。

results matching ""

    No results matching ""