【问题标题】:Making changes to Core Data fetched array更改 Core Data 获取的数组
【发布时间】:2023-04-05 01:03:01
【问题描述】:

这是我所拥有的:

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 工作并反映在 UI 中。但是,当我退出应用程序并返回时,arrayOfTags 缺少我添加的那个(但它有另外两个,所以我知道数组工作正常)。由于某种原因,它没有保存。

NoteObjectNSManagedObject 的子类,arrayOfTags 是实体的可转换属性。)

我在这里做错了吗?

编辑:这是我添加新注释的方法,即使使用 arrayOfTags 也可以很好地保存,当我退出应用程序并返回时,所有内容都会保存。

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]);
        }

只有当我进行更改时,它才没有正确保存..

【问题讨论】:

  • 只是一个字符串..我还不确定,但我认为我的问题可能是我没有使用 fetchedResultsController
  • 这似乎更有可能是您的 arrayOfTags 实现中的问题 - 您能否提供更多详细信息?

标签: objective-c core-data


【解决方案1】:

您的意思是您使用的是 Transformable 属性吗? 这有帮助吗: Core Data saving problem: can't update transformable attribute (NSArray)

【讨论】:

  • 是的,这是同样的问题。我不明白他的解决方案。他到底做了什么?
【解决方案2】:

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

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]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    • 2014-01-29
    相关资源
    最近更新 更多