[英]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.