Rigtht way to implement Aysnchronous Delegate Methods

耗尽温柔 提交于 2019-12-13 17:27:26

问题


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


回答1:


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.




回答2:


- (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.



来源:https://stackoverflow.com/questions/4154167/rigtht-way-to-implement-aysnchronous-delegate-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!