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?
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.
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.
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;
}
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