0

Inside a ViewController with ARC (.m file has compiler flags in Build Phases -fobjc-arc -fobjc-arc-exceptions)

As I know apple recommend to use weak ref for self inside a block like this

self __weak typeof(self) weakSelf = self;

In some case weakSelf is nil inside block, I have few e.g.

e.g.1

__weak typeof(self) weakSelf = self;

CLGeocoder *ceo = [[CLGeocoder alloc]init];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:lat longitude:lon];

[ceo reverseGeocodeLocation: loc completionHandler:
         ^(NSArray *placemarks, NSError *error) {
             CLPlacemark *placemark = [placemarks objectAtIndex:0];

                //some logic here using weakSelf
                 => weakSelf nil
}

e.g.2

__block id weakSelf = self;
CLGeocoder *ceo = [[CLGeocoder alloc]init];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:lat longitude:lon];

[ceo reverseGeocodeLocation: loc completionHandler:
         ^(NSArray *placemarks, NSError *error) {
             CLPlacemark *placemark = [placemarks objectAtIndex:0];

                //some logic here using weakSelf
                 => weakSelf nil
}  

e.g. 3

__weak typeof(self) weakSelf = self;
__block id safeBlockSelf = self;
CLGeocoder *ceo = [[CLGeocoder alloc]init];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:lat longitude:lon];

[ceo reverseGeocodeLocation: loc completionHandler:
         ^(NSArray *placemarks, NSError *error) {
             CLPlacemark *placemark = [placemarks objectAtIndex:0];

                //some logic here using safeBlockSelf
                 => weakSelf NOT nil
}

Some Ideas why weakSelf is nil?

Alex
  • 8,908
  • 28
  • 103
  • 157

1 Answers1

1

The weakSelf reference is nil because it got deallocated. If it wasn't nil your app would crash. If you need it to be not nil retain it with a local strong reference inside the block. Like this:

__strong typeof(weakSelf) strongSelf = weakSelf;
Andrey Chernukha
  • 21,488
  • 17
  • 97
  • 161
  • thanks for your answer, but weakSelf inside of the block is nil, non sense to assign nil to strong __strong typeof(weakSelf) strongSelf = weakSelf; in case I use __strong typeof(self) strongSelf = self; outside of the block, inside the block strongSelf is not null – Alex Jul 29 '19 at 06:52
  • edit your answer to put outside of the block strong, and I will mark as correct answer – Alex Jul 29 '19 at 06:53