简体   繁体   中英

Does Core Data persist the order of objects in NSMutableArray?

I basically operate on objects in a NSMutableArray, which is fetched from Core Data. All changes to those objects save in Core Data with the exception of the order of objects in the array. When, for instance, an object in the array is moved to the end of it, that does not seem to save in Core Data. Is it the case that Core Data does not persist order of objects in arrays? If so, what can be done to work around it? Sorting?

This is how I fetch data:

    NSError *error;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"Item" inManagedObjectContext:managedObjectContext];

    [fetchRequest setEntity:entity];
    self.items = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];

And this is how I save changes:

- (void)saveCoreData{

    NSManagedObjectContext *context = [self managedObjectContext];

    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Could not save data: %@", [error localizedDescription]);
    }

}

If you're saving the array in a transform able property on an entity then the order will be saved - if you set the array back onto the managed object instance.

If the array is a fetched list of managed object instances then the order of that array means nothing and won't be saved. If you want to save this order then you need to add (and update) some other data in the context. This could be an order attribute on the entity or another entity with an ordered relationship perhaps.

If you're not using ordered relationships, then there is no guarantee of the order.

You can either set your relationships to be ordered. In this case you will have to deal with NSOrderedSet and different accessory methods. This feature is available in iOS5 and later. Here is a great article of Ash Furrow (great developer, had a privilege to meet him) that covers ordered relationships in Core Data.

On the other hand, you can order your data once you access it. In my case I had an NSArray property that, once accessed, would get all objects in NSSet and order them. The disadvantage of this approach is every time you add new NSManagedObject to a relationship, mentioned NSArray will become outdated and must be recreated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM