开发者

Checking if an object has been released before sending a message to it

开发者 https://www.devze.com 2023-01-02 11:41 出处:网络
I\'ve only recently noticed a crash in one of my apps when an object tried to message its delegate and the delegate had already been released.

I've only recently noticed a crash in one of my apps when an object tried to message its delegate and the delegate had already been released.

At the moment, just before calling any delegate methods, I run this check:

if (delegate && [delegate respondsToSelector:...]){
   [delegate ...];
}

But obviously this doesn't account for if the delegate isn't nil, but has been deallocated.

Besides setting the object's delegate to nil in the delegate's dealloc method, is there a way to check if the delegate has already been released just incase I no longer have a开发者_运维问答 reference to the object.


No. There is no way to tell whether a variable points to a valid object. You need to structure your program so that this object's delegate isn't going away without letting it know first.


I assume you're not using GC. In that case, standard convention is that the code that sets the delegate is responsible for setting the delegate-user's reference to nil before allowing the delegate to be deallocated. If you're using GC, you can use a __weak reference for the delegate, allowing the garbage collector to set the reference to nil when the instance is garbage collected.


how about using a counter that you increment everytime you alloc and decrement everytime you dealloc. That way you could detect double allocs and could decide not to use a delegate if the counter isnt nil but the address isnt nil also


for debug proposes you can override release method on your class to see when it is called.

-(oneway void)release
{
    NSLog(@"release called");
    [super release];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消