Saving yourself 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
  • Is this the correct way to access sselffrom the main queue block?
  • Did you manage to sselfget out of scope after the completion of the initial queue?
  • Should I add a second __typeof__(self) sself = wself;to the main queue block?
+3
source share
2 answers

You are asking:

Is this the correct way to access sselffrom the main queue block?

Nearly. You must also check that it is sselfnot nil. You do this because dereferencing ivar for a pointer nilcan crash your application. Thus, make sure that it is not nil:

- (void) doSomething
{
    typeof(self) __weak wself = self;
    dispatch_async(dispatch_get_global_queue(0,0), ^{
       typeof(self) sself = wself;
       if (sself) {
           [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];
           });
        }
    });
}

:

sself ?

, , .

__typeof__(self) sself = wself; ?

, , . . , , , ( ) , sself ( , , , dataArray), , weakSelf/strongSelf.

+1
  • , .
  • , main_queue.
  • , . __typeof__(self) sself = wself; global_queue; , wself ( , self __typeof__(self) ).
  • __typeof__. typeof(self)
+2

All Articles