gpt4 book ai didi

ios - NSFetchRequest 有时只返回结果

转载 作者:行者123 更新时间:2023-11-29 12:43:50 24 4
gpt4 key购买 nike

关于这个问题,我正在回答我自己的问题。在我看到尽可能多的其他答案之前,我不会接受它。

在过去的几天里,我一直在努力处理下面的代码

- (id)fetchUniqueEntity:(Class)entityClass
withValue:(id)value
fromContext:(NSManagedObjectContext *)context
insertIfNil:(BOOL)insertIfNil {
if(!value) {
return nil;
}

NSString *entityUniqueIdentifierKey = [entityClass performSelector:@selector(uniqueIdentifierKey)];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %@", entityUniqueIdentifierKey, value];

NSArray *entities = [self fetchEntities:entityClass
withPredicate:predicate
fromContext:context];

if(!entities || [entities count] == 0) {
if (insertIfNil) {
return [entityClass performSelector:@selector(insertInManagedObjectContext:)
withObject:context];
}
} else {
return [entities objectAtIndex:0];
}

return nil;
}

- (NSArray *)fetchEntities:(Class)entityClass
withPredicate:(NSPredicate *)predicate
fromContext:(NSManagedObjectContext *)context {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSString *entityName = [entityClass performSelector:@selector(entityName)];
[request setEntity:[NSEntityDescription entityForName:entityName
inManagedObjectContext:context]];
if(predicate) {
[request setPredicate:predicate];
}

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

if(error) {
NSLog(@"Error executing fetch request for %@! \n\n%@", entityName, error);
}

return entities;
}

top helper 方法旨在帮助在大型下载过程中建立关系。我遇到的问题是,即使说在持久存储(已确认)中有一个 Account 对象的 accountId1,它只是在一半的时间里检索那个对象。老实说,我无法解释为什么。有什么想法吗?

最佳答案

经过多次调试和反复试验,我发现将谓词格式从

[NSPredicate predicateWithFormat:@"%K == %@", entityUniqueIdentifierKey, value];

[NSPredicate predicateWithFormat:@"%K == %d", entityUniqueIdentifierKey, [value intValue]];

解决了这个问题。在研究了 apple 文档之后,似乎 %@ 应该可以工作。所以我不是 100% 确定为什么这解决了问题。

关于ios - NSFetchRequest 有时只返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24158618/

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