Skip to content

Instantly share code, notes, and snippets.

@victorchee
Last active August 29, 2015 14:08
Show Gist options
  • Save victorchee/c6c789b9f6c528773986 to your computer and use it in GitHub Desktop.
Save victorchee/c6c789b9f6c528773986 to your computer and use it in GitHub Desktop.
iOS关联对象
#import "ViewController.h"
#import <objc/runtime.h>
@interface ViewController () <UIAlertViewDelegate>
@end
static void *MyAlertViewKey = "MyAlertViewKey";
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Question"
message:@"What do you want to do?"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Continue", nil];
void (^block)(NSInteger) = ^(NSInteger buttonIndex){
if (buttonIndex == 0) {
NSLog(@"cancel");
} else {
NSLog(@"continue");
}
};
objc_setAssociatedObject(alert, MyAlertViewKey, block, OBJC_ASSOCIATION_COPY);
[alert show];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - alert view delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
void (^block)(NSInteger) = objc_getAssociatedObject(alertView, MyAlertViewKey);
block(buttonIndex);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment