[英]Put Core Data values in an array
I need to put the values retrieved using a Fetch Request from my core data graph into an array, but not entirely sure how to go about this. 我需要将使用提取请求从我的核心数据图中获取的值放入一个数组中,但不能完全确定如何执行此操作。
I'm using the following to perform the fetch: 我正在使用以下内容执行提取:
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];
As you can see, i'm filtering the values that come back using an NSPredicate. 如您所见,我正在过滤使用NSPredicate返回的值。
How would I get these values into an array and also be able to select individual attributes for the entity once they are in the array, for example the project.description or project.name? 如何将这些值放入数组中,以及如何将实体中的各个属性(例如project.description或project.name)放入数组中?
Thanks to Eimantas I've got the objects in an array, however I still need to do two things: 感谢Eimantas,我将对象放置在一个数组中,但是我仍然需要做两件事:
I'm using the following for loop to do the first: 我正在使用以下for循环来执行第一个:
for (int i=0; i < [projectListArray count]; i++)
{
NSString *tmp = (NSString *)[projectListArray objectAtIndex:i];
}
However, this is returning the error: 但是,这将返回错误:
-[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'
It appears as though i might not be incrementing? 好像我可能没有增加?
[self.fetchedResultsController fetchedObjects]
returns the array of fetched objects. [self.fetchedResultsController fetchedObjects]
返回获取的对象数组。
update 更新
It's better to use fast enumaration, not a for
loop: 最好使用快速枚举,而不是
for
循环:
for (Project *project in projectListArray) {
NSString *projectDescription = [project valueForKey:@"description"];
}
You're getting the exception because you're casting an object to NSString
while it's a pointer to (I presume) Project
managed object. 之所以会出现异常,是因为您正在将对象转换为
NSString
同时它是指向(我认为) Project
管对象的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.