Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retaining self with nested blocks?

With the following code:

@interface MyClass()
{
   NSMutableArray * dataArray;
}
@end

@implementation MyClass

- (void) doSomething
{
    __typeof__(self) __weak wself = self;
    dispatch_async(dispatch_get_global_queue(0,0), ^{
       __typeof__(self) sself = wself;
       [sself->dataArray addObject: @"Hello World"];

       dispatch_async(dispatch_get_main_queue(), ^{
         [NSThread sleepForTimeInterval: 30];

         UIAlertView *alert = [[UIAlertView alloc] initWithTitle: sself->dataArray[0] 
                                                         message: @"Message"
                                                        delegate: nil
                                               cancelButtonTitle: @"OK"
                                               otherButtonTitles: nil];
         [alert show];
       });
    });
}

@end
  1. Is this the proper way to access sself from within the main queue block?
  2. Would sself go out of scope once the initial queue finished?
  3. Should I add a second __typeof__(self) sself = wself; inside the main queue block?
like image 685
Kyle Avatar asked Jan 01 '26 20:01

Kyle


1 Answers

  1. Yes, sure it is.
  2. No, you'll be able to use in main_queue block.
  3. No, you don't have to. You don't have to add __typeof__(self) sself = wself; even in global_queue block; it's not necessary, you already have a weakened self object wself (moreover, you will retain self in __typeof__(self) part inside the block).
  4. You don't have to use __typeof__. Use simply typeof(self)
like image 175
Maciej Oczko Avatar answered Jan 03 '26 10:01

Maciej Oczko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!