更改核心数据提取数组 [英] Making changes to Core Data fetched array

查看:58
本文介绍了更改核心数据提取数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我所拥有的:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription 
                               entityForName:@"NoteObject" inManagedObjectContext:appDelegate.managedObjectContext];

[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(parentNoteId == %@) AND (noteId!=rootNoteId)", appDelegate.currentNoteId];
[fetchRequest setPredicate:predicate];
NSError *error;

[appDelegate.arrayOfNotes setArray:[appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error]];

NoteObject *note=[appDelegate.arrayOfNotes objectAtIndex:0];
[note.arrayOfTags addObject:someObject];

NSManagedObjectContext *context = [appDelegate managedObjectContext];
if (![context save:&error]) {
    NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}

提取工作正常,并将对象添加到 arrayOfTags 可以在用户界面中反映出来。但是,当我退出应用程序并返回时, arrayOfTags 缺少我添加的一个(但是它具有另外两个,所以我知道数组可以正常工作) 。

The fetch works fine, and adding an object to the arrayOfTags works and reflects in the UI. However, when I exit the app and come back, the arrayOfTags is missing the one that I added (but it has the other two, so I know the array is working properly). It's not saving for some reason.

NoteObject NSManagedObject <的子类。 / code>和 arrayOfTags 是实体的可转换属性。)

(The NoteObject is a subclass of NSManagedObject, and arrayOfTags is a transformable property of the entity.)

我在做什么在这里错了吗?

Am I doing something wrong here?

编辑:这是我添加新笔记的方式,即使保存了arrayOfTags,也可以很好地保存它,并且在退出应用程序并返回时一切都保存了

Here's how I add a new note, which saves just fine, even with the arrayOfTags, and everything is saved when I exit the app and come back in.

NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *noteEntity = [[appDelegate.managedObjectModel entitiesByName] objectForKey:@"NoteObject"];
NoteObject *tempNote = [[NoteObject alloc] initWithEntity:noteEntity insertIntoManagedObjectContext:context];
[tempNote.arrayOfTags addObject:@"tag1"];
NSError *error;
        if (![context save:&error]) {
            NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
        }

仅当我进行更改时,它才能正确保存。.

It's only when I make changes that it's not saved properly..

推荐答案

原来,我要做的就是在对数组进行更改后重新设置数组:

Turns out all I had to do was re-set the array after making changes to it:

NoteObject *tempNote = [[NoteObject alloc] initWithEntity:noteEntity insertIntoManagedObjectContext:context];
[tempNote.arrayOfTags addObject:@"tag1"];

[tempNote setArrayOfTags:tempNote.arrayOfTags]; //this is the magic line

NSError *error;
if (![context save:&error]) {
       NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}

这篇关于更改核心数据提取数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆