上代码:
resDict = [[NSMutableDictionary alloc] init];
[resDict removeAllObjects];
[resDict removeAllObjects];
resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
<pre name="code" class="objc">[resDict removeAllObjects];
当运行时就会报错,为什么?
其实 第一个 [resDict removeAllObjects]; 是没问题的;
第二个 [reDict removeAllObjects]; 有问题, 到底为什么呢?
看看报错信息显示:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary removeAllObjects]: mutating method sent to immutable object'
看看,我没会发现:'-[__NSCFDictionary removeAllObjects]: mutating method sent to immutable object';
这句是其中的重点:原来是可变的方法,发送到不可变的变量上,导致了错的出现;
其实真正的是:
resDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
resDict 是指针,其指向了不可变的内存之中,所以用mutable 的方法会发生错误;
xiaohonqi
转载请注明出处