开发者

Why must I make an mutable copy of this array?

开发者 https://www.devze.com 2022-12-18 05:25 出处:网络
开发者_如何学GoApple provided this example: NSError *error; NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];

开发者_如何学GoApple 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;
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号