我正在尝试从Core Data中读取数组。我的代码如下
-(NSArray *)getAges
{
NSArray *fetchedObjects = [[NSArray alloc] init];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context = nil;
context = [[NSManagedObjectContext alloc] init];
@try {
NSPersistentStoreCoordinator *tempCordinator = (NSPersistentStoreCoordinator *)[(AppDelegate *)[[UIApplication sharedApplication] delegate] persistentStoreCoordinator];
[context setPersistentStoreCoordinator:tempCordinator];
NSError *error;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Age"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
}
@catch (NSException *exception) {
NSLog(@"core data exception occured.");
fetchedObjects = nil;
}
[fetchRequest release];
[context release];
return fetchedObjects;
}
现在在主线程中,在IBAction方法中,我写下面的行。
[NSThread detachNewThreadSelector:@selector(loadAgesMethod) toTarget:self withObject:nil];
问题是这个方法返回了一个包含20个元素的数组。我可以看到数组计数20但是在调试器中,对于数组的每个元素,我看到'超出范围'和'摘要不可用'。当我尝试从这个数组中获取任何对象时,我什么也得不到。有一点需要提一下,就像我上面提到的那样,我从一个辅助线程调用loadAgesMethod中的方法getAges。这是我的要求。此外,当我尝试从主线程中检索此数组时,我完全可以获得所有数据。
任何人都可以给我一个提示,我错了吗?
祝你好运
答案 0 :(得分:0)
每个NSManagedObject都有一个NSManagedObjectContext属性。这用于在将来需要时懒惰地获取对象的属性。在此方法结束时,您调用[context release],因此将释放NSManagedObjectContext,并且您的Age对象的所有NSManagedObject上下文属性都将为nil。
您可以在上下文中调用[context autorelease],以便它在方法之后持续一段时间,并允许您在稍后阶段获取对象的属性。请注意,这只会持续到自动释放池在运行循环结束时消失。我仍然在尝试为多线程提取提供更好的解决方案。