开发者

iphone: Core Data: NSManagedObjects and UITableView crash

开发者 https://www.devze.com 2023-04-11 14:01 出处:网络
This fetch method work perfectly and the NSLog prints out the contents of the database...(fetchedObjects in an NSArray):

This fetch method work perfectly and the NSLog prints out the contents of the database...(fetchedObjects in an NSArray):

NSError *error2;
fetchedObjects = [moc executeFetchRequest:fetchRequest error:&error2];

if (!fetchedObjects) {
    NSLog(@"Error %@",[error2 localizedDescription]);
}

for (NSManagedObject *info in fetchedObjects) {

    NSLog(@"Name: %@", [info valueForKey:@"Name"]);
    NSLog(@"Description: %@", [info valueForKey:@"Description"]);
    NSLog(@"Ingredients: %@", [info valueForKey:@"Ingredients"]);

.. but when I try to populate a tableView (I have built many tables and feel i have a good understanding of how they work), the program crashes with a "EXE_BAD_ACCESS at int retVal = UIApplicationMain(argc, argv, nil, nil);." That is it, no other error messages.

To try and debug, I put this simple NSLog in the "cellForRowAtIndexPath" method, but it crashes at NSLog(@"fetchedObjects count in tableview %i",[fetchedObjects count]).

I haven't released the array as far as I can tell.

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

    // Configure the cell.
    NSLog(@"fetchedObjects count in tableview %i",[fetchedObjects count]);
    NSManagedObject *info3 = [fetchedObjects objectAtIndex:in开发者_如何转开发dexPath.row];
    NSLog(@"Name: %@", [info3 valueForKey:@"Name"]);
    cell.textLabel.text = [info3 valueForKey:@"Name"];


Looks like your fetchedObjects instance variable is being deallocated because of an autorelease pool flush.

NSManagedObjectContext's -executeFetchRequest:error: method returns an autoreleased NSArray instance, which you aren't obtaining ownership of, therefore by the time execution reaches the -tableView:cellForRowAtIndexPath: method, the autorelease pool has been flushed, and that object is deallocated, and you now have a dangling pointer. Ah, classic.

The solution, of course, is to send the -retain message to the returned NSArray from sending -executeFetchRequest:error: to your NSManagedObjectContext.

Don't forget to send the -release message to it in your -dealloc method.


The problem seems to be on this line

NSManagedObject *info3 = [fetchedObjects objectAtIndex:indexPath.row];

Try to use

NSManagedObject *info3 = [fetchedObjects objectAtIndex:0];

Because your UiTableViewCell count and fetchedObjects count should be equal at whole process.

If it doesn't match then it will give you index error.

0

精彩评论

暂无评论...
验证码 换一张
取 消