使用objc_getAssociatedObject在應(yīng)用里出現(xiàn)崩潰,在此記錄一下。
我在ViewController中做了測(cè)試,ViewController.m 在 Compiles Sources 里需要加上 -fno-objc-arc
#import "ViewController.h"
#import <objc/runtime.h>
@interface ViewController ()
@end
@implementation ViewController
//1.聲明一個(gè)靜態(tài)變量,用作關(guān)鍵字.此處也可以直接用一個(gè)字符串(但不推薦)
static char overViewKey;
- (void)viewDidLoad {
[super viewDidLoad];
//2.創(chuàng)建一個(gè)數(shù)組變量
NSArray * array =[[NSArray alloc] initWithArray:@[@"one",@"two",@"three"]];
//3.創(chuàng)建一個(gè)字符串變量;為了演示的目的,這里使用initWithFormat:來(lái)確保字符串可以被銷毀
NSString * overview = [[NSString alloc] initWithFormat:@"%@",@"First three numbers"];
//4.關(guān)聯(lián)代碼操作(關(guān)鍵);第四個(gè)參數(shù)用 OBJC_ASSOCIATION_RETAIN_NONATOMIC,也可以嘗試 OBJC_ASSOCIATION_ASSIGN 第六步會(huì)crash。
objc_setAssociatedObject(array, &overViewKey, overview, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
//5.釋放overview
[overview release];
//6.訪問(wèn)已經(jīng)被我釋放的對(duì)象
NSLog(@"%p ~~ overview= %@",overview,overview);
//7.釋放array
[array release];
//8.訪問(wèn)array
NSLog(@"%p ~~ array= %@",array,array);
//9.訪問(wèn)overview
NSLog(@"%p ~~ overview= %@",overview,overview);
}
@end