我正在尝试稍微清理一下我的代码,并且我想到了创建一个小帮助器类来保存和从核心数据中获取数据。
我在助手类中执行 NSFechtRequest,如下所示:
- (NSArray *)fetchDataOutOfDBWithEntity:(NSString *)description
{
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"HealthData" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *results = [context executeFetchRequest:fetchRequest error:&error];
return results;
}
这只会返回一个 NSArray
,如果您使用 executeFetchRequest:error:
我从 UICollectionsViewController 的 viewDidLoad
方法中调用此函数,如下所示:
- (void)viewDidLoad {
[super viewDidLoad];
DatabaseHelper *helper = [[DatabaseHelper alloc] init];
NSArray *array = [helper fetchDataOutOfDBWithEntity:@"HealthData"];
dataInHealth = [[[NSArray alloc] initWithArray:array];
}
现在奇怪的是 dataInHealth 包含信息。我可以将它们打印出来,并且可以在我返回的数组中看到 NSManagedObjects(通过断点),但是当我想将信息插入到 collectionView 中时,它只是不执行任何操作或抛出一些疯狂的异常(取决于我在做什么)。
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
KalenderCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
HealthData *object = [dataInHealth objectAtIndex:indexPath.row];
cell.stepCount.text = object.stepCount;
return cell;
}
object.stepCount
只是零,我拥有的所有其他属性保持不变。为什么我不能访问我的属性。当我除了从 viewDidLoad 中获取而不是从辅助类中获取任何东西时,一切都是开箱即用的。
那个NSArray里面有数据。为什么我无法访问它?
最佳答案
尝试将 DatabaseHelper 对象变成一个属性,我认为当 viewDidLoad 结束执行时你的托管对象上下文被释放,同时释放你通过它获取的所有 ManagedObjects。
关于ios - 核心数据助手类返回对象 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29918298/