How to determine if I have a pointer to released object?

前端 未结 3 554
南方客
南方客 2020-12-21 06:34

In a function I am processing an object which may be corrupted sometimes, at runtime, can I somehow determine whether or not my object is corrupted?

3条回答
  •  眼角桃花
    2020-12-21 06:56

    The only way to really do this is to leverage a new thing with ARC (and iOS 5, doesn't work before this) called __weak pointers.

    It should also be noted that __weak variables do not retain, by definition. If a __weak variable retained it's target, then by definition, it couldn't release itself.

    Basically, a __weak pointer is a variable that automatically set's itself to NULL when it is deallocated. Thus, you can do something like this to determine if an object is deallocated:

    __strong id object; // required so that the object doesn't get deallocated right away
    __weak id _weakRef;
    
    object = [NSObject new];
    _weakRef = object;
    
    // do stuff with 'object'
    
    if (_weakRef)
    {
        // 'object' hasn't been deallocated yet, do something with it.
    }
    

    Normally speaking, you don't hold onto a strong and weak reference to an object, however, as this causes _weakRef to be useless (just check when you set object to nil).

    I would also caution against having a design pattern based solely on __weak variables, especially if you are making a framework. Nothing says 'Annoying' like having to use iOS 5 as your target deployment.

    I hope this post helped you get a deeper understanding of how weak references work, and if not, there is an excellent wikipedia article you can read here:

    http://en.wikipedia.org/wiki/Weak_reference

提交回复
热议问题