_01_《高性能iOS应用开发》——内存管理

2017-06-27  本文已影响24人  饮长刀

- (NSString *)address {
    NSString *ad = [[[NSString alloc] initWithString:@"贝克街 221B"] autorelease];
    return ad;
}
...
- (void)showPersonAddress:(Person *)p {
    NSString *address = [p address];
    NSLog(@"Person's Address: %@", address);
}

- (void)startCountdown {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateFeed:) userInfo:nil repeats:YES];
}

- (void)dealloc {
    [self.timer invalidate];
}

很明显上面的例子中产生了循环引用,直到 [self.timer invalidate] 执行,timer 才会取消对 self 的强引用,但是由于建立了循环引用,这里的 dealloc 并不会调用,timer 并不会执行 invalidate。所以需要自定义一个清理的方法执行清理操作。这样的清理方法可以在离开当前页面点击返回时调用。
另一种清理方案是将持有关系分散到多个类中——任务类执行具体动作,所有者类调用任务。类似于将 taget 设置为任务类的代理。

上一篇 下一篇

猜你喜欢

热点阅读