Hob*_*ige 8 objective-c ios objective-c-blocks
我已经阅读了Apple的Blocks Programming Topics和我的尽职调查在线搜索,但我仍然不清楚我是否正确实现我的块.我有一组客户端作为在发送NSNotification时填充的属性.客户端用作tableview数据源.下面的代码有效,但我很好奇是否将自我置于保留周期.我应该做类似的事情__block id theClients = self.clients;,然后theClients在街区内引用吗?
@property (strong, nonatomic) NSMutableArray *clients;
NSNotificationCenter *notifyCenter = [NSNotificationCenter defaultCenter];
__block id observer = [notifyCenter addObserverForName:queryHash
object:nil
queue:[[NSOperationQueue alloc] init]
usingBlock:^(NSNotification* notification){
// Explore notification
if ([[notification.userInfo objectForKey:kdatasetReturnKey] objectAtIndex:0]) {
NSArray *rows = [[notification.userInfo objectForKey:kdatasetReturnKey] objectAtIndex:0];
if (self.clients)
{
self.clients = nil;
}
self.clients = [[NSMutableArray alloc] initWithCapacity:rows.count];
for (NSDictionary *row in rows) {
[self.clients addObject:row];
}
} else {
NSLog(@"CLIENTS ERROR Returned: %@",[notification.userInfo objectForKey:kerrorReturnKey]);
}
[[NSNotificationCenter defaultCenter] removeObserver:observer];
}];
Run Code Online (Sandbox Code Playgroud)
访问clients属性没有问题,因为它是一个强大的(即保留的)属性.所以你不需要__block这里.
一个问题self可能是在发送通知时可能不再存在.然后你将访问解除分配的对象,应用程序可能会崩溃!为避免这种情况,您应该删除dealloc方法中的观察者.
在__block以前id observer是绝对必需的!
编辑:
在iOS 5中,您可以self使用弱引用安全地捕获:
__weak id weakSelf = self;
Run Code Online (Sandbox Code Playgroud)
然后在块内你可以安全地使用weakSelf.clients.当对象被释放时,变量weakSelf将自动变为nil.
| 归档时间: |
|
| 查看次数: |
6767 次 |
| 最近记录: |