ARC管理Objective-C對象類型,可是非對象類型的數據,好比struct就不是ARC的管理對象,在使用的時候,就須要咱們來手動管理。spa
下邊,咱們的使用情景是這樣的,定一個一個結構體,用來存儲一些數據,而後把結構體放在NSArray中。個人寫法是這樣的,debug
1 typedef struct { 2 __unsafe_unretained NSString * itemName; 3 __unsafe_unretained NSString * imageNameSel; 4 __unsafe_unretained NSString * imageNameDis; 5 NSInteger tag; 6 } SportChooseInfo; 7 8 @interface ViewController () { 9 NSMutableArray *sportArray; 10 } 11 12 @end 13 14 @implementation ViewController 15 16 - (void)viewDidLoad { 17 [super viewDidLoad]; 18 19 sportArray = [[NSMutableArray alloc] init]; 20 SportChooseInfo _run = {@"跑步", @"icon_sport_choose_paobu_sel", @"icon_sport_choose_paobu_dis", 0}; 21 SportChooseInfo _walk = {@"走路", @"icon_sport_choose_walk_sel", @"icon_sport_choose_walk_dis", 1}; 22 23 [sportArray addObject:[NSData dataWithBytes:&_run length:sizeof(SportChooseInfo)]]; 24 [sportArray addObject:[NSData dataWithBytes:&_walk length:sizeof(SportChooseInfo)]]; 25 } 26 27 28 - (IBAction)testAction:(id)sender { 29 for (int i=0; i<sportArray.count; i++) { 30 SportChooseInfo info; 31 [sportArray[i] getBytes:&info length:sizeof(SportChooseInfo)]; 32 NSLog(@"itemName:%@, imageNameSel:%@, imageNameDis:%@, tag:%ld,", info.itemName, info.imageNameSel, info.imageNameDis, info.tag); 33 } 34 }
使用完 _run和_walk之後,嘗試着free(&_run);,提示錯誤指針
CollectionViewDemo(10961,0x1065d3000) malloc: *** error for object 0x7fff5cafe820: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug
沒錯,提示咱們並無爲_run和_walk分配內存。。。。。。,也就是說,_run和_walk並不在內存當中,準確的說,是不在堆中,而是存放在了棧中,棧中的數據不須要咱們作手動內存管理,想想int類型的數據,是否是就明白了。那struct如何申請堆內存呢?作法以下:code
1 typedef struct { 2 __unsafe_unretained NSString * itemName; 3 __unsafe_unretained NSString * imageNameSel; 4 __unsafe_unretained NSString * imageNameDis; 5 NSInteger tag; 6 } SportChooseInfo; 7 8 @interface TestViewController () { 9 SportChooseInfo * test; 10 } 11 12 @end 13 14 @implementation TestViewController 15 16 - (void)loadView { 17 [super loadView]; 18 UIView *view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 19 [view setBackgroundColor:[UIColor blueColor]]; 20 [self setView:view]; 21 22 test = malloc(sizeof(SportChooseInfo)); 23 test->itemName = @"test"; 24 25 NSLog(@"itemName:%@", test->itemName); 26 27 free(test); 28 }
首先咱們定一個結構體指針,而後分配內存,內存的大小爲結構體的大小,使用完結構體數據之後,必定要記得手動free,不然就會出現內存泄漏。對象
以上。blog