tags:

views:

637

answers:

3

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.

A: 

It's not working because arrayWithArray is a class method, not an instance method.

You can do [NSMutableArray arrayWithArray:arrayCountryChoices] to do what you need.

You could just call [arrayCountryChoices mutableCopy] to return a new mutable array with the contents of arrayCountryChoices.

Jasarien
+4  A: 

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.

Can Berk Güder
//copy the original array to searchable array arraySearchResults = [[NSMutableArray alloc] initWithArray:arrayCountryChoices];Worked like a champ. Thanks.
you're welcome.
Can Berk Güder
+1  A: 

You can also create empty mutable array and add objects to it using -addObjectsFromArray method

Vladimir