Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone SDK: How to copy the contents of a NSArray to NSMutable array?

Tags:

iphone

I need to copy the contents of an NSArray to NSMutable array. In other words, I want to copy arrayCountryChoices to arraySearchResults. Any ideas????

//main data
NSArray *arrayCountryChoices;

//search results buffer 
NSMutableArray *arraySearchResults;


//create data 
arrayCountryChoices = [[NSArray alloc] initWithObjects:@"foo",@"bar",@"baz",nil];   

//copy the original array to searchable array ->> THIS  IS NOT WORKING AS EXPECTED
arraySearchResults = [[NSMutableArray alloc] arrayWithArray:arrayCountryChoices];

Thanks in advance.

like image 340
user265550 Avatar asked Feb 05 '10 18:02

user265550


1 Answers

it's either

[NSMutableArray arrayWithArray:anArray];

or

[[NSMutableArray alloc] initWithArray:anArray];

or

[anArray mutableCopy];

The code in your example doesn't work because you're calling arrayWithArray on an instance of NSMutableArray, but arrayWithArray is a class method.

As a general rule, initalization methods that start with init are instance methods, and those that start with the name of the class (array, etc.) are class methods. Class methods return autoreleased objects, while instance methods return retained objects.

like image 184
Can Berk Güder Avatar answered Nov 15 '22 20:11

Can Berk Güder