[英]mutating method sent to immutable object' in nsmutablearray
我想從 NSmutableArray 中刪除對象可以告訴我從 NSMutableArray 中刪除的最佳方法
。H
@property(nonatomic,retain)NSMutableArray *arr_property;
.m
_arr_property=[[NSMutableArray alloc]init];
MTPop *lplv = [[MTPop alloc] initWithTitle:SelectProperty(APP_SHARE.language)
options:[_arr_property valueForKeyPath:@"property_list.property_type_name"]
handler:^(NSInteger anIndex) {
txt_Property.text=[[_arr_property valueForKeyPath:@"property_list.property_type_name"] objectAtIndex:anIndex];
NSLog(@"index number %ld",(long)anIndex);
刪除對象--->>>
NSLog(@"index number %@",[_arr_property valueForKey:@"property_list"]);
[[_arr_property valueForKeyPath:@"property_list.property_type_name"] removeObjectAtIndex:anIndex]; ////hear the app is crashing
應用程序崩潰錯誤我得到的是
2015-06-09 13:21:31.104 Estater[2170:62264] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object'
想想你的代碼:
_arr_property=[[NSMutableArray alloc]init];
你現在有一個空的NSMutableArray。 它沒有元素。
[... removeObjectAtIndex:0];
我們剛剛說什么? 該數組沒有元素。 它沒有元素 0 - 要擁有元素 0,它至少需要有一個元素,但事實並非如此。 沒有什么可以刪除的。
[_arr_property valueForKeyPath:@"property_list.property_type_name"]
那部分是最奇怪的,但讓我們繼續。 當在數組上調用valueForKeyPath:
時,會生成 NSArray - 而不是 NSMutableArray。 所以這會給你一個空的 NSArray 。 但是你不能對 NSArray 說removeObjectAtIndex:
即使它是空的——它不是可變的。 這就是你正在經歷的崩潰。
真正的錯誤是您在 NSMutableArray 的元素上調用 removeObject:
[-->[_arr_property valueForKeyPath:@"property_list.property_type_name"]<-- removeObjectAtIndex:0];
數組看起來是空的,但如果填充了一些東西,要刪除第一個元素,你應該這樣做:
[_arr_property removeObjectAtIndex:0];
首先,您不能使用NSMutableArray
進行它不支持的鍵值編碼。 你必須更好地使用NSMutableDictionary
。 字典基於鍵存儲對象,而數組基於索引存儲對象。
您可以像這樣使用 NSMutableDictionary:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:something forKey:@"Some Key"];
// ... and later ...
id something = [dict objectForKey:@"Some Key"];
其次, valueForKeyPath:
返回一個值而不是數組, valueForKey:
返回鍵值的數組,並且該數組是不可變的。
編輯:
第三,在對valueForKeyPath:
進行了更多研究后,發現它在集合操作和使用語法中的用途 is 。 所以,通過改變來做到
[_arr_property valueForKeyPath:@"property_list.property_type_name"]
到
[_arr_property valueForKeyPath:@"@property_list.property_type_name"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.