ARC模式下struct类型数据的内存管理

  ARC管理Objective-C对象类型,但是非对象类型的数据,比如struct就不是ARC的管理对象,在使用的时候,就需要我们来手动管理。

  下边,我们的使用情景是这样的,定一个一个结构体,用来存储一些数据,然后把结构体放在NSArray中。我的写法是这样的,

 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如何申请堆内存呢?做法如下:

 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,否则就会出现内存泄漏。

  以上。

posted @ 2016-03-16 16:22  i左撇子  阅读(659)  评论(0编辑  收藏  举报