Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert NSArray to NSMutableArray

Tags:

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

like image 538
Ali Avatar asked Dec 31 '10 10:12

Ali


People also ask

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

What is NSMutableArray?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray .

Is NSArray ordered?

The answer is yes, the order of the elements of an array will be maintained - because an array is an ordered collection of items, just like a string is an ordered sequence of characters...

How do I create an NSArray in Objective C?

Creating an Array Object The NSArray class contains a class method named arrayWithObjects that can be called upon to create a new array object and initialize it with elements. For example: NSArray *myColors; myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];


1 Answers

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.

like image 188
sean woodward Avatar answered Oct 22 '22 06:10

sean woodward