UsingBlocksAsContextInfo - Demonstrates how to implement Objective-C "blocks" passed in as the 'contextInfo' to NSAlert, helping to handle the alert result.
// This is a quick tip on how to use the context info as a block parameter.
// You can use this type of pattern for any methods that have a delegate/selector/contextInfo pattern.
- (void)btnShowAlertClicked:(id)sender {
NSAlert *alert = [NSAlert alertWithMessageText:@"Alert Message"
defaultButton:@"Default Button"
alternateButton:@"Alternate Button"
otherButton:@"Other Button"
informativeTextWithFormat:@"Informative Text"];
BOOL someLocalVariable = YES;
// We create a block that can easily access local variables to this method.
// This is much easier than trying to package them all up into a contextInfo object
void (^blockCallback)(NSInteger) = ^(NSInteger returnCode) {
// Inside the block callback we can easily access locals
if (someLocalVariable) {
if (returnCode == NSAlertDefaultReturn) {
[button setTitle:@"Default Return Button Clicked!"];
} else {
[button setTitle:@"Something else clicked...try again."];
}
}
};
// We copy the block, since it needs to stay alive for longer than the current scope
[alert beginSheetModalForWindow:self.window
modalDelegate:[self class]
didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)
contextInfo:Block_copy(blockCallback)];
}
+ (void)alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void (^)(NSInteger returnCode))continuationHandler {
continuationHandler(returnCode);
// The block must always be retained before the first call. This is the matching release
Block_release(continuationHandler);
}

Leave a comment