[英]Put Core Data values in an array
我需要将使用提取请求从我的核心数据图中获取的值放入一个数组中,但不能完全确定如何执行此操作。
我正在使用以下内容执行提取:
NSString *entityName = @"Project"; // Put your entity name here
NSLog(@"Setting up a Fetched Results Controller for the Entity named %@", entityName);
// 2 - Request that Entity
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
// 3 - Filter it if you want
request.predicate = [NSPredicate predicateWithFormat:@"belongsToProject = %@", _selectedProject];
// 4 - Sort it if you want
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"dateTaken"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)]];
// 5 - Fetch it
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
[self performFetch];
如您所见,我正在过滤使用NSPredicate返回的值。
如何将这些值放入数组中,以及如何将实体中的各个属性(例如project.description或project.name)放入数组中?
感谢Eimantas,我将对象放置在一个数组中,但是我仍然需要做两件事:
我正在使用以下for循环来执行第一个:
for (int i=0; i < [projectListArray count]; i++)
{
NSString *tmp = (NSString *)[projectListArray objectAtIndex:i];
}
但是,这将返回错误:
-[Project length]: unrecognized selector sent to instance 0x1b9f20
2012-03-28 10:48:35.160 Project App[3973:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Project length]: unrecognized selector sent to instance 0x1b9f20'
好像我可能没有增加?
[self.fetchedResultsController fetchedObjects]
返回获取的对象数组。
更新
最好使用快速枚举,而不是for
循环:
for (Project *project in projectListArray) {
NSString *projectDescription = [project valueForKey:@"description"];
}
之所以会出现异常,是因为您正在将对象转换为NSString
同时它是指向(我认为) Project
管对象的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.