Question

I have a block attached to a button (using this category):

__unsafe_unretained typeof(UIImage) *weakPic = originalPic;
[button addEventHandler:^{
    switch (state) {
    case state1:
        {
           UIViewController *vc = //some VC
           vc.pic = weakPic; // weakPic is nil at this point
                             // putting originalPic here would solve my problem
                             // but then I would have a retain cycle


        }  

    case state2:
        {
          // other stuff
        }
    }

}];

the action associated with the button is different depending on the state.

Here is the problem: I must keep the above __unsafe_unretained to avoid having a retain cycle. However, this code is called at a point where originalPic = nil.. and so when I assign weakPic to vc.pic I'm assigning it a nil value. If I replace weakPic with just originalPic, then it works fine.. (originalPic will have the updated value) but then I get the retain cycle.. ideas?

Was it helpful?

Solution

Without knowing more about your code I suggest you consider declaring a weakSelf and implementing an accessor on self.

//the accessor
-(UIImage*)pic{
    return originalPic;
}

-(void)someSetupMethod{
    __weak id weakSelf = self;

    [button addEventHandler:^{
        switch (state) {
        case state1:
            {
               UIViewController *vc = //some VC
               vc.pic = [weakSelf pic]; // if weakself is nil at this point, then
                                        // originalPic is likely invalid


            }  

        case state2:
            {
              // other stuff
            }
        }

    }];
}

It may not be a weakSelf you want, but some other object. In that case just declare that other object to be weak, as long as you can be relatively sure it will exist as long or longer than the button.

OTHER TIPS

You might also want to look at declaring it as a __block variable. The __block keyword prevents a copy of the object from being made inside the block.

See this thread for a better explanation of __weak and __block references.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top