Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must I make an mutable copy of this array?

Apple provided this example:

NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
    // Handle the error
}

Why are they calling mutableCopy here? Is it because they wanted to have an NSMutableArray rather than an NSArray, to edit / change it later? Or is there another reason?

like image 537
openfrog Avatar asked Jan 25 '10 16:01

openfrog


3 Answers

The answer can be found further up in the article that provided your example:

When the table view controller loads its view, it should fetch the Event objects and keep them in the events array so that they can be displayed later. The events array needs to be mutable since the user can add and remove events.

The block of code in your example is one part of a multi-part process of fetching managed objects from a persistent store. The next step in the process will call setEventsArray:, which requires a mutable array.

like image 139
e.James Avatar answered Nov 16 '22 17:11

e.James


If I remember correctly using [myObject copy] creates an immutable copy of the object by default, so if you have NSMutableArray it becomes NSArray.

Because in this example you want to keep the mutability, and hence the ability to manipulate, the array you call [myObject mutableCopy]; to ensure that you get a mutable copy of the object.

like image 3
James Avatar answered Nov 16 '22 18:11

James


This sample code probably comes from "Core Data Tutorial for iPhone" of Apple's documents. If so, the reason why they did mutableCopy is they need the NSMutableArray to the ivar which is defined as NSMutableArray.

The sample code set mutableFetchResults to the instance variable like as follows.

[self setEventsArray:mutableFetchResults];
[mutableFetchResults release];
[request release];

Then, the instance variable is defined like as follows.

@interface RootViewController : UITableViewController <CLLocationManagerDelegate> {

    NSMutableArray *eventsArray;
    NSManagedObjectContext *managedObjectContext;

    CLLocationManager *locationManager;
    UIBarButtonItem *addButton;
}
like image 2
tomute Avatar answered Nov 16 '22 17:11

tomute