OC高効率52は、既存クラスにおいて関連オブジェクトを用いてカスタムデータを格納する
2235 ワード
#import "ViewController.h"
#import <objc/runtime.h>
//objc_AssociationPolicy
static void *EocMyAlertViewKey = @"EocMyAlertViewKey";
@interface ViewController ()<UIAlertViewDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
// Do any additional setup after loading the view, typically from a nib.
//
// objc_setAssociatedObject(id object, <#const void *key#>, <#id value#>, <#objc_AssociationPolicy policy#>)
// objc_getAssociatedObject(id object, <#const void *key#>)
// objc_removeAssociatedObjects(<#id object#>)
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(200, 200, 100, 200)];
button.backgroundColor = [UIColor orangeColor];
[self.view addSubview:button];
[button addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];
}
-(void)action
{
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 ){
[self doCancel:alert];
}
else
{
[self doContinue];
}
};
//1. , “ ” “ ”
objc_setAssociatedObject(alert, EocMyAlertViewKey, block,OBJC_ASSOCIATION_COPY);
[alert show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//2.
void (^block)(NSInteger) = objc_getAssociatedObject(alertView, EocMyAlertViewKey);
block(buttonIndex);
//3. , bug
}
-(void)doCancel:(UIAlertView *)alert
{
NSLog(@"Calcel");
objc_removeAssociatedObjects(alert);
}
-(void)doContinue
{
NSLog(@"doContinue");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end