gpt4 book ai didi

ios - 如何从核心数据中获取数据并在表格 View 中显示 iOS 6

转载 作者:行者123 更新时间:2023-12-01 16:47:47 24 4
gpt4 key购买 nike

我已成功将通讯簿数据存储在 Core Data 中,但我无法检索它并将其显示在 tableView 中。我错过了什么?

这就是我从核心数据中获取数据的方式。

-(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];

这是我的表格 View 配置。
 - (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;
}

最佳答案

正如讨论结果,self.arrayForTableviewWillAppear 中的空数组替换获取 fetchFromDatabase 中的对象后.

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

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

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

    关于ios - 如何从核心数据中获取数据并在表格 View 中显示 iOS 6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18557736/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com