NSMutableArray,NSMutableDictionary的内存管问题

今天做项目遇到一个问题,在一个类中定义了一个可变数组,使用的是copy的内存管理策略

当往数组中添加包装好的基本数据的时候,程序直接崩溃了。解决方法:把copy换成strong就不会崩溃了;

后来做了个测试,并没有很清楚问题出在哪里,如果有人知道请指教

 

新建一个工程 Single View Application

新建一个Pesrson类

Person.h

@interface Person : NSObject

@property (nonatomic, copy) NSMutableArray *testArr;
@property (nonatomic , copy) NSMutableDictionary *testDic;

@end

Person.m

@implementation Person

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.testArr = [NSMutableArray array];
        self.testDic = [NSMutableDictionary dictionary];
    }
    return self;
}

@end

 ViewController.m

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    Person *person = [[Person alloc] init];
    
    [person.testArr addObject:[NSValue valueWithCGRect:CGRectZero]];
    
}


@end

 运行后程序崩溃,

reason: '-[__NSArray0 addObject:]: unrecognized selector sent to instance 0x7f83b25009f0

只要是向可变字典/可变数组 中添加NSValue类型的对象,都会出现这种情况;

然后我新建了一个Command Line Toll

同样新建一个Person类做同样的测试(使用copy的内存管理策略)

main.m

int main(int argc, const char * argv[]) {
    @autoreleasepool {
       
        Person *p1 = [[Person alloc] init];
        [p1.testArr addObject:[NSValue valueWithRect:CGRectZero]];
        NSLog(@"%@",p1.testArr);
    }
    return 0;
}

 打印结果

2016-01-21 00:17:42.953 test[1465:80006] (

    "NSRect: {{0, 0}, {0, 0}}"

)

可以正常打印,一直没明白这当中问题出在哪里,如果有人知道请指教

 

--------------------------------------------------------------已解决:

copy拷贝出来的是一个不可变数组,对它添加元素就会造成crash

 

posted on 2016-01-21 00:23  利利利  阅读(590)  评论(0编辑  收藏  举报

导航