How to convert NSArray to NSMutableArray

痞子三分冷 提交于 2020-01-01 04:00:07

问题


ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);  
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);

NSMutableArray *tempPeoples=[[NSMutableArray alloc]init];

for(int i=0;i<nPeople;i++){

    ABRecordRef i1=CFArrayGetValueAtIndex(allPeople, i);
    [tempPeoples addObject:i1];

//  [peoples addObject:i1];

}// end of the for loop
peoples=[tempPeoples copy];

This code gives exception b/c I want to convert NSMutableArray to NSArray Please Help


回答1:


The subject reads, "How to convert NSArray to NSMutableArray". To get an NSMutableArray from an NSArray, use the class method on NSMutableArray +arrayWithArray:.

Your code does not show the declaration for peoples. Assuming it's declared as an NSMutableArray, you can run into problems if you try to treat it as such. When you send the copy message to an NSMutableArray, you get an immutable object, NSArray, so if you try to add an object to a copied NSMutableArray, you will get an error.

CFArrayRef is toll free bridged to NSArray, so you could simplify your code this way:

CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
//NSMutableArray *tempPeoples = [NSMutableArray arrayWithArray:(NSArray*)allPeople];
// even better use the NSMutableCopying protocol on NSArray
NSMutableArray *tempPeoples = [(NSArray*)allPeople mutableCopy];
CFRelease(allPeople);
return tempPeoples; // or whatever is appropriate to your code

In the above code tempPeoples is an autoreleased NSMutableArray ready for you to add or remove objects as needed.




回答2:


This code gives exception b/c I want to convert NSMutableArray to NSArray

This is very unlikely. NSMutableArray is a derived class of NSArray, so copying in that direction isn't an issue.

Maybe you've got an error because you don't retain the array. arrayWithArray returns an autorelease object. Either use [tempPeoples copy] or [[NSArray alloc] initWithArray: tempPeoples];




回答3:


Simply you can do that

NSArray *yourArray ; // Static Array
NSMutableArray* subArrayData = [yourArray mutableCopy];


来源:https://stackoverflow.com/questions/4569478/how-to-convert-nsarray-to-nsmutablearray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!