我在我的测试项目中使用核心数据。 我能够将内容从json添加到核心数据实体'Book'。但是当我尝试检索数据时,我只获取最后一个'数据'(总共37个数据)? 我创建了一个mutablearray'director'来插入每个检索到的值,但这也没有用。
请检查我的代码。
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
directors=[[NSMutableArray alloc]init];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Book" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
NSLog(@"1");
[directors addObject:[info valueForKey:@"director"]];
NSLog(@"Name: %@", info);
}
NSLog(@"%@",directors);
正在打印'NSLog(@"1");
以检查循环工作的次数,但是
我正在获得这样的输出
2014-06-15 15:40:03.665 test[12489:1303] Name: <Book: 0x8c50580> (entity: Book; id: 0x8c66a60 <x-coredata://EEF91D97-C982-40E1-A898-9E646D206B39/Book/p1> ; data: <fault>)
2014-06-15 15:40:03.665 test[12489:1303] 1
2014-06-15 15:40:03.666 test[12489:1303] Name: <Book: 0x8c690d0> (entity: Book; id: 0x8c68420 <x-coredata://EEF91D97-C982-40E1-A898-9E646D206B39/Book/p2> ; data: <fault>)
2014-06-15 15:40:03.666 test[12489:1303] 1
2014-06-15 15:40:03.667 test[12489:1303] Name: <Book: 0x8f9c8d0> (entity: Book; id: 0x8d89870 <x-coredata://EEF91D97-C982-40E1-A898-9E646D206B39/Book/p3> ; data: {
actors = "Hazel Crowney, Kiran Kumar, Shahbaaz Khan, Usha Bachani, Mohammed Iqbal Khan, Alka Verma";
censor = U;
director = "Arshad Yusuf Pathan";
global = N;
lang = Hindi;
length = "";
rating = 0;
releasedate = "13th Jun 2014";
synopsis = "The story of a racecar driver who loses his eyesight. While he suffers a setback, he learns about the true value of the relationships in his life. Through the course of the film, the hero realizes the";
title = Unforgettable;
trailer = "";
type = MT;
url = "http://cnt.in.bookmyshow.com/Events/Mobile/ET00022474.jpg?dtm=15614303";
})
当前代码
答案 0 :(得分:1)
正如我从日志中看到的那样,除了最后一个之外,你从CoreData收到的所有托管对象都是错误的。这意味着这些对象是表示实体(Book)的适当类的实例,但它们未初始化。如果您尝试访问某些已接收记录的字段,它们将自动初始化。 我想你的代码的以下修改应该有效:
for (Book *info in fetchedObjects) {
NSLog(@"1");
[directors addObject:info.director];
NSLog(@"Name: %@", info);
}
NSLog(@"%@",directors);
此处Book
是继承自NSManagedObject
的类,表示名为Book
的实体。您可以通过突出显示CoreData模型中的实体并从 Editor 菜单中选择 Create NSManagedObject subclass 项来为任何实体生成此类。
有关错误的更多信息:Core Data Programming Gudie