2013-09-01 60 views
2

我已经成功地将地址簿数据存储在核心数据中,但我无法检索它并将其显示在tableView中。我缺少什么?如何从核心数据中提取数据并在表格中显示查看iOS 6

这是我如何从核心数据中获取数据。

-(void)fetchFromDatabase 
{ 
    AddressBookAppDelegate *appDelegate =[[UIApplication sharedApplication]delegate]; 
    NSManagedObjectContext *context = [appDelegate managedObjectContext]; 
    NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"AddressBook" inManagedObjectContext:context]; 
    NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
    [request setEntity:entityDesc]; 

    NSError *error; 
    self.arrayForTable = [context executeFetchRequest:request error:&error]; 
    NSLog(@"fetched data = %@",[self.arrayForTable lastObject]); //this shows the data 
    [self.tableView reloadData]; 

这是我的表视图配置。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [self.arrayForTable count]; 
} 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
    reuseIdentifier:CellIdentifier]; 

    if ([self.arrayForTable count]>0) 
    { 
     NSLog(@" table view content = %@",[self.arrayForTable lastObject]);// this doesn't log 
     AddressBook *info = [self.arrayForTable objectAtIndex:indexPath.row]; 
     cell.textLabel.text = info.firstName; 

    } 
    } 
    return cell; 
} 
+0

尝试在''fetchFromDatabase'方法的末尾添加'[self.tableView reloadData]'。 - 您还应该考虑使用NSFetchedResultsController在表格视图中显示Core Data对象。 –

+0

我更新了[self.tableView reloadData];方法 。但结果是一样的。 – icodes

+0

是否调用了'numberOfRowsInSection'和'cellForRowAtIndexPath'? –

回答

0

正如在讨论翻出来,self.arrayForTableviewWillAppear替换为空数组fetchFromDatabase获取的对象之后。

另一个问题是,程序的每次运行都会在数据库中创建新对象,导致重复的对象为 。您可以

  • 插入新的对象,或
  • 为每名前删除所有对象,检查是否有匹配对象在数据库中已存在,并插入仅在需要一个新的。

在“核心数据编程指南”中的"Implementing Find-or-Create Efficiently"中描述了更高级的技术。

相关问题