Tomohisa Takaoka
Tomohisa Takaoka

Reputation: 885

iOS 5 blocks crash only with Release Build

I have using blocks and ARC, and found in some situation, iOS only crash in Release build. It was wrong way to write code, like this.

-(IBAction)clickedButtonA:(UIBarButtonItem*)sender event:(UIEvent*)event {
  NSMutableArray *arrRows = [NSMutableArray arrayWithCapacity:0];
  #warning this code only crash on Release Build.... Don't use this
  NSMutableDictionary * dicRow = [NSMutableDictionary dictionaryWithCapacity:0];
  [arrRows addObject:dicRow];
  dispatch_block_t block = ^{
    NSString *str = [NSString stringWithFormat:@"%@",[_tweet valueForKey:@"text"]];
    [[UIPasteboard generalPasteboard] setString:str];
  };
  [dicRow setValue:block forKey:kDicKeyLinkPopBlock];

  NSMutableArray *sections = [NSMutableArray arrayWithObject:arrRows];
  TOVLinkPopoverViewController *controller= [[TOVLinkPopoverViewController alloc] init];
  controller.arrayLink = sections;
}

And from other controller, when I access the block, it crashes only I am on release build. I have learn you need to copy the block

[dicRow setValue:[block copy] forKey:kDicKeyLinkPopBlock];

For non-block aware Class like NSMutableDictionary.

The question is "Why it only crashes on Release build?" I know this "should crash", and this was wrong way of using block, but hoping it crashes on Debug build so we can find this kind of bug earlier.

One more question is "Is there any build setting that makes this code crash with debug build?"

You can ran sample code from gitHub, https://github.com/tomohisa/iOS_PopoverMenu_Notification

See ViewController.m and find commented out code (only crash on release).

Upvotes: 1

Views: 870

Answers (1)

mattjgalloway
mattjgalloway

Reputation: 34902

You're right that you need to add [block copy]. This is because that block is created in the current stack frame (i.e. within clickedButtonA:event:) but then you add it to a dictionary and presumably pull it out later. When you pull it out later and use it, that original stack frame has gone and you will have a pointer to some random memory that might not (most likely won't) actually be the block any more.

When you copy the block, if it's on the stack currently then it gets copied to the heap and if it's already on the heap then it just retains it. This means that you now have a block which can be passed around between contexts and will be valid.

The reason that you are only seeing it crash in release mode is because release mode will be turning on compiler optimisation that is completely changing how the stack is handled. Probably you were very lucky in debug mode not to see the problem and was simply a quirk of how your app is designed.

Upvotes: 6

Related Questions