我在我的应用程序中使用coredata来存储data.i必须在一个视图控制器中添加数据并在另一个视图控制器中检索它。我尝试了以下代码,但它无法正常工作。
//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,我能够检索这些值。
答案 0 :(得分:0)
将值存储在视图中的Mutable Array中,并在您检索值的位置加载。然后在表视图中使用它。将noof Rows声明为数组计数。
答案 1 :(得分:0)
看起来你没有使用ARC。我认为你需要在viewDidLoad中保留你的获取请求的结果(不要忘记在dealloc中释放它)。此外,您通过alloc / initing数组然后覆盖它来泄漏。