Rigtht way to implement Aysnchronous Delegate Meth

2019-07-25 00:05发布

Consider 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

2条回答
The star\"
2楼-- · 2019-07-25 00:10

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.

查看更多
时光不老,我们不散
3楼-- · 2019-07-25 00:24
- (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.

查看更多
登录 后发表回答