Transitioning to ARC causing delegate issues

非 Y 不嫁゛ 提交于 2019-12-23 17:07:42

问题


After transitioning a project to ARC, I've been having some issues with delegate methods not being called/being called on deallocated instances. I've realized that the problem is that I have a variable that gets allocated and then executes an asynchronous task. For a simple example, assume that there is an object called MyService that responds to a delegate method, executeDidSucceed:

- (void)fireRequest {
    MyService *service = [[MyService alloc] initWithDelegate:self];
    [service execute];
} 

The original code would look something like this:

- (void)fireRequest {
    MyService *service = [[[MyService alloc] initWithDelegate:self] autorelease];
    [service execute];
} 

With ARC, I understand that a release call gets added after [service execute] gets called. And I also understand that because the method is asynchronous, the service object will get deallocated, and a call to the deallocated object will be made for the delegate method.

I know a solution would be to make service an instance variable and give it the strong property so we can retain ownership of it. And I know of a solution where we could create a block and use a completion handler so the delegate stays retained until the block is completed. My question is, what's the best way of handling a situation like this? Or more so, what's the "best practice" for resolving this while transitioning to ARC?


回答1:


You will need to make your Myservice object a member to this class. ARC is cleaning it up as soon as this function completes because you no longer have a reference to it.

It's also my opinion that its a good practice to do since you don't have a reference to that object until it calls a delegate (if it does) and depending on the situation you may need stop the service before it completes.



来源:https://stackoverflow.com/questions/12786748/transitioning-to-arc-causing-delegate-issues

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