Search code examples
iosnullnsobjectperformselector

Perform selector when object is not nil ios


I habe an object ImageURLObject, this object have property objectUrlImage, when I create this object property objectUrlImage is nil, becourse image url has not setted yet, how can I perform selector when property has actual value? It's not a method [self performSelector: withObject: afterDelay:]because I don't know after what delay property become not nil..


Solution

  • You can use Key-Value Observing (KVO) to detect a change to a property of an object.

    In the setter of the ImageURLObject you need to perform the notification using willChangeValueForKey and didChangeValueForKey:

    - (void)setObjectUrlImage:(NSURL *)url
    {
        [self willChangeValueForKey:@"objectUrlImage"];
        _objectUrlImage = url;
        [self didChangeValueForKey:@"objectUrlImage"];
    }
    

    and establish an observation of that property from where ever it is you want:

    [imageUrlObject addObserver:self
                     forKeyPath:@"objectUrlImage"
                        options:NSKeyValueObservingOptionNew
                        context:NULL];
    

    and observations will be notified in the following method:

    - (void)observeValueForKeyPath:(NSString *)keyPath
                          ofObject:(id)object
                            change:(NSDictionary *)change
                           context:(void *)context
    {
        if (object == imageUrlObject && [keyPath isEqualToString:@"objectUrlImage"])
        {
            // URL changed
        }
    }
    

    Don't forget to remove the observation of the property in the dealloc method of the observer:

    - (void)dealloc
    {
        [imageUrlObject removeObserver:self
                            forKeyPath:@"ObjectUrlImage"];
    }
    

    (note that this is one of the few reasons to subclass dealloc in an ARC environment).