Rigtht way to implement Aysnchronous Delegate Methods
Conside开发者_C百科r the following situation.
-(void) foo {
Object * obj = [[Object alloc] init];
obj.delegate = self;
[obj excuteAsync];
}
-(void) delegateMethodReturned {
// do something
}
Here executeAync returns aynchronously after sometime. Thus we cannot release obj safely. What is the best design pattern to implement such a situation without declaring obj as an iVar.
Thanks
If you can target iOS4 you could circumvent the asynchronous callback using blocks and GCD.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^ {
Object * obj = [[Object alloc] init];
[obj excuteSync];
// do something
[obj release];
});
I have found this helpful in some situations but your mileage may vary.
- (void) delegateMethodReturned: (Object *)obj {
[obj release];
}
However, the static analyser will complain about that, because it thinks you leaked obj
in -foo
, which you did.
精彩评论