我正在尝试从我的coredatabase中获取单个对象,但它会一直返回null。我的方法是基于另一个方法,它返回我正在访问的coredata对象的每个值..
我之前从未尝试过这种方法并试过阅读苹果文档,但它只是没有意义..这就是我的方法看起来像
- (NSMutableArray *)readSelectedInstall:(NSString *)projIDString {
NSManagedObjectContext *context = [self managedObjectContext];
if (context == nil) {
NSLog(@"Nil");
}
else {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"InstallProject" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ProjID==%@", projIDString];
[fetchRequest setPredicate:predicate];
NSError *error;
NSMutableArray *installProjectDictionaryArray = [[NSMutableArray alloc] init];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (InstallProject *installProj in fetchedObjects) {
NSMutableDictionary *tempInstallProjectDictionaryArray = [[ NSMutableDictionary alloc] init];
[tempInstallProjectDictionaryArray setObject:installProj.companyName forKey:@"CompanyName"];
[tempInstallProjectDictionaryArray setObject:installProj.projNo forKey:@"ProjNo"];
[tempInstallProjectDictionaryArray setObject:installProj.projID forKey:@"ProjID"];
[installProjectDictionaryArray addObject:tempInstallProjectDictionaryArray];
}
return installProjectDictionaryArray;
}
return nil;
}
任何让我返回projID与projIDString匹配的单项的帮助将不胜感激。
答案 0 :(得分:17)
导入NSManagedObject(InstallProject)并获取一个这样的对象,
-(InstallProject *)readSelectedInstall:(NSString *)projIDString
{
NSArray *fetchedObjects;
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"InstallProject" inManagedObjectContext: context];
[fetch setEntity:entityDescription];
[fetch setPredicate:[NSPredicate predicateWithFormat:@"(ANY ProjID contains[cd] %@)",projIDString]];
NSError * error = nil;
fetchedObjects = [context executeFetchRequest:fetch error:&error];
if([fetchedObjects count] == 1)
return [fetchedObjects objectAtIndex:0];
else
return nil;
}
答案 1 :(得分:11)
fetchLimit
fetchRequest
怎么样你可以设置为 1
获取限制指定请求在执行时应返回的最大对象数。
EG。在斯威夫特:
let fetchRequest = NSFetchRequest(entityName: "Cart")
fetchRequest.fetchLimit = 1
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
编辑: sortDescriptors的设置只是因为我将这个fetchRequest与NFRC一起使用,你也可以执行fetchRequest:
do {
let fetchRequest = NSFetchRequest(entityName: "Cart")
fetchRequest.fetchLimit = 1
fetchRequest.predicate = NSPredicate(format: "name == %@", mainCart)
var objects: [Cart]
try objects = mainMoc.executeFetchRequest(fetchRequest) as! [Cart]
} catch {
}