Search code examples
objective-cnsmutablearraynsarray

How to convert NSArray to NSMutableArray


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


Solution

  • 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.