ios - Can't convert this snippet to Objective C - ARC -


i have convenient class when want call alert in button this:

- (ibaction)test:(id)sender {     [myalertview showwithtitle:@"test" withcallbackblock:^(int value){         nslog(@"button pressed %i", value);      }]; } 

the class simple:

    @implementation myalertview @synthesize callbackblock = _callbackblock, internalcallbackblock = _internalcallbackblock;  -(void)showwithtitle:(nsstring *)title withcallbackblock:(callbackblock )callbackblock internalcallbackblock:(callbackblock )internalcallbackblock{     self.callbackblock = callbackblock;     self.internalcallbackblock = internalcallbackblock;      dispatch_async(dispatch_get_main_queue(), ^{         uialertview *alertview = [[uialertview alloc] initwithtitle:title message:title delegate:self cancelbuttontitle:@"cancel" otherbuttontitles:@"ok" , nil];         [alertview show];         [alertview autorelease];     });  }  - (void)alertview:(uialertview *)alertview clickedbuttonatindex:(nsinteger)buttonindex{     if (_callbackblock) {         _callbackblock(buttonindex);     }      if (_internalcallbackblock) {         _internalcallbackblock(buttonindex);     } }   -(void)dealloc{     block_release(_callbackblock);     block_release(_internalcallbackblock);     [super dealloc]; }   +(void)showwithtitle:(nsstring *)title withcallbackblock:(callbackblock )callbackblock{     __block myalertview *alert = [[myalertview alloc]init];     [alert showwithtitle:title withcallbackblock:callbackblock internalcallbackblock:^(int value){         [alert autorelease];     }];  } @end 

i've profiled on simulator , shows no leaks, no zombies. now, when change arc, program crashes every time click test button, though reference strong. i'm guessing thats because i'm not holding alertview variable.

how can 1 convenience class arc ?

appending .h file:

#import <foundation/foundation.h>  typedef void(^callbackblock)(int value);  @interface myalertview : nsobject<uialertviewdelegate>   @property (copy) callbackblock callbackblock, internalcallbackblock;  +(void)showwithtitle:(nsstring *)title withcallbackblock:(callbackblock )callbackblock; @end 

you're right: problem uialertview created in showwithtitle:withcallbackblock:internalcallbackblock:internalcallbackblock not being retained.

the trick store @ instance variable of myalertview. in myalertview.m, add following:

@interface myalertview()     @property(strong) uialertview *alertview; @end  @implementation myalertview  @synthesize alertview;  ... 

and use store uialertview create in showwithtitle:withcallbackblock:internalcallbackblock:internalcallbackblock:

dispatch_async(dispatch_get_main_queue(), ^{     self.alertview = [[uialertview alloc] initwithtitle:title message:title delegate:self cancelbuttontitle:@"cancel" otherbuttontitles:@"ok" , nil];     [self.alertview show]; }); 

p.s. going pedantic, myalertview isn't view might want rename it.


Comments