views:

633

answers:

4

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?

A: 

It's hard to say why they did it without seeing the example. The only reason to do it would be to make a copy of the array that you can modify. But, if your intent is just to read through the fetched items, then there's no need to make a copy, mutable or otherwise.

Alex
+2  A: 

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;
}
tomute
+4  A: 

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.

e.James
“The next step in the process will call `setEventsArray:`, which requires a mutable array.” Which sucks: Anything that obtains `eventsArray` can mutate it without its owner's knowledge. The safe way to do things is for the array property to be publicly immutable, with the class's accessors being the only way to mutate the array. This copy is necessary (moving it into `setEventsArray:` would be no slower), and the one in the getter (to return an immutable copy of the mutable array) can be cut if such an optimization really is warranted.
Peter Hosey
+1  A: 

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.

James Raybould