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
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.
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 .
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...
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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With