gpt4 book ai didi

ios - CoreData 在 NSFetchRequest 找到新对象之前需要一些时间

转载 作者:行者123 更新时间:2023-11-29 03:28:39 26 4
gpt4 key购买 nike

我的应用程序中有一个表单,允许用户输入文本并将其保存到 UIManagedDocument 中的 CoreData

当应用程序正在运行时,我使用 NSManagedObjectContext 作为唯一的上下文,用于从该文档中插入和获取对象。

我遇到的问题是 - 在保存之前我会检查重复项,如果我在等待 10 秒后进行后续插入,context 不会确认已插入([匹配计数] 返回 0) 个对象,并允许重复。

另一方面,如果我等待它 - 结果如预期([matches count] 返回任何数字为真)。

完整代码

@implementation Student (Create)

+ (Student *)withInfo:(NSDictionary *)infoDictionary inManagedContext:(NSManagedObjectContext *)context
{
Student *student = nil;

// Check for duplicates
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
request.predicate = [NSPredicate predicateWithFormat:@"studentID == %@", (NSString *)infoDictionary[@"studentID"]];
[request includesPendingChanges];

NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];

if (!matches || ([matches count] > 1)) {
// handle error
NSLog(@"Error happens");
for (Student *student in matches) {
[context deleteObject:student];
NSLog(@"studentID: %@", student.studentID);
}
} else if (![matches count]) {
student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:context];

NSString *studentID = (NSString *)infoDictionary[@"studentID"];
int studentIDint = [studentID intValue];
NSLog(@"studentID: %d", studentIDint);

student.studentID = [NSNumber numberWithInt:studentIDint];
student.nameFirst = infoDictionary[@"nameFirst"];
student.nameLast = infoDictionary[@"nameLast"];

// Add this students portrait as a relationship
Portrait *portrait = [Portrait portraitWithAssetURL:infoDictionary[@"PortraitAssetURL"] inManagedObjectContext:context];
student.portrait = portrait;

NSError *errorSave;
[context save:&errorSave];
NSLog(@"errorSave: %@", errorSave);

NSLog(@"creating a new student, matches count: %lu", (unsigned long)[matches count]);
} else {
student = [matches lastObject];
NSLog(@"fetching old one, count: %lu", (unsigned long)[matches count]);
}

return student;
}

@end

最佳答案

代码应如下所示:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"EntityName"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uniqueID == %@", newID]
[request setPredicate:predicate];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];

if([matches count]){
// update record
SomeEnt *ent = [matches objectAtIndex:0];
// ent set properties
}
else{
// add new record
SomeEnt *ent = [NSEntityDescription insertNewObjectForEntityForName:@"EntityName" inManagedObjectContext:context];
// ent set properties
// ...
}
NSError *error;
[context save:&error];

关于ios - CoreData 在 NSFetchRequest 找到新对象之前需要一些时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20118235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com