我在我的应用程序中使用 coredata 来存储数据。我必须在一个视图控制器中添加数据并在另一个视图控制器中检索它。我尝试了以下代码,但它不起作用。
//addViewController.m
-(IBAction)save:(id)sender
{
CoreDataOneAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *newContact;
newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Employee"
inManagedObjectContext:context];
[newContact setValue:name.text forKey:@"name"];
[newContact setValue:amount.text forKey:@"amount"];
name.text = @"";
amount.text = @"";
//label
status.text = @"saved";
NSError *error;
[context save:&error];
}
我想检索值并将它们显示在 tableView
//retrieveViewController.m
- (void)viewDidLoad
{
objects = [[NSArray alloc]init];
CoreDataOneAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Employee"
inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSError *error;
objects = [context executeFetchRequest:request
error:&error];
[request release];
[super viewDidLoad];
}
//tableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [objects count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
labelOne = [[UILabel alloc]initWithFrame:CGRectMake(5, 11, 110, 21)];
labelTwo = [[UILabel alloc]initWithFrame:CGRectMake(230, 11, 70, 21)];
static NSString *cellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier]autorelease];
}
[cell.contentView addSubview:labelTwo];
[cell.contentView addSubview:labelOne];
NSManagedObject *matches = nil;
matches = [objects objectAtIndex:indexPath.row];
NSString *str1=[NSString stringWithFormat:@"%@",[matches valueForKey:@"name"]];
labelOne.text = str1;
NSString *str2=[NSString stringWithFormat:@"%@",[matches valueForKey:@"amount"]];
labelTwo.text = str2;
return cell;
}
我收到 EXC_BAD_ACCESS 错误。我尝试使用 NSZombieEnabled 并收到以下错误。
2012-04-27 11:59:18.153 CoreDataOne[4370:207] *** -[_PFArray objectAtIndex:]: message sent to deallocated instance 0x5931e40
如果在 cellForRowAtIndexPath 中编写我在 viewDidLoad 中编写的代码,但如何声明 numberOfRows,我能够检索这些值。