ID:[...] 的 NSManagedObject 已失效

Posted

技术标签:

【中文标题】ID:[...] 的 NSManagedObject 已失效【英文标题】:The NSManagedObject with ID:[...] has been invalidated 【发布时间】:2011-02-07 20:06:41 【问题描述】:

我正在使用核心数据构建应用程序。由 appDelegate 加载的我的 RootViewController 主要来自模板。但是我已将实体名称更改为“时钟”并添加了一堆行。

我的 RootViewController 展示了一个具有 UINavigationController 的 MVC。当我将数据保存到我的数据库时,UINavigationController 类使用[[UIApplication sharedApplication]delegate] 保存了数据,以访问我的 appDelegate,它实际上执行了保存操作。 编辑数据的方式相同,但不是在我的应用委托中调用插入函数,而是调用更新函数。

现在,这一切都很好……实际上非常完美。但是......几次打开编辑并保存在视图中后,我的应用程序崩溃了。它在模拟器和我的 iPhone 4 上都这样做。这是我的意思的一个例子(电影):http://dl.dropbox.com/u/3077127/has_been_invalidated.mov

这是我的 RootViewController.m 的代码:

#import "RootViewController.h"
#import "RootViewControllerClockCell.h"
#import "RootViewControllerClockCellFooter.h"
#import "configuration.h"
#import "AddClockViewController.h"
#import "clockAppDelegate.h"

#import "AddClockNavigationController.h"

@interface RootViewController ()
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
@end


@implementation RootViewController

@synthesize fetchedResultsController=fetchedResultsController_, managedObjectContext=managedObjectContext_;


#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad 
    [super viewDidLoad];

    [self setTitle:NSLocalizedString(@"Alarms", @"AddClockNavigationController")];

    // Set up the edit and add buttons.
    self.navigationItem.leftBarButtonItem = self.editButtonItem;

    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showAddAlarmView)];
    self.navigationItem.rightBarButtonItem = addButton;
    [addButton release];

    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    [self.tableView setBackgroundView:[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"clockTableBackground"]] autorelease]];
    [self.tableView setAllowsSelectionDuringEditing:YES];

    if (managedObjectContext_ == nil) 
     
        managedObjectContext_ = [(ClockAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
        NSLog(@"After managedObjectContext: %@",  managedObjectContext_);
    

    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate=self;
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;

    [locationManager startUpdatingLocation];


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 

    location = newLocation.coordinate;
    [locationManager stopUpdatingLocation];

    [self.tableView reloadData];


- (void)viewWillDisappear:(BOOL)animated

    [locationManager stopUpdatingLocation];

    [super viewWillDisappear:animated];



// Implement viewWillAppear: to do additional setup before the view is presented.
- (void)viewWillAppear:(BOOL)animated 
    [locationManager startUpdatingLocation];

    [super viewWillAppear:animated];


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
    if ([Configuration isIpad])
    
        return YES;
    
    else 
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
    


- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath 

    // @TODO
    // Remove unused function


- (void)showAddAlarmView

    AddClockNavigationController *viewController = [[AddClockNavigationController alloc] initWithNibName:@"AddClockNavigationController" bundle:nil];

    [[self navigationController] presentModalViewController:viewController animated:YES];
    [viewController release];


#pragma mark -
#pragma mark Add a new object

- (void)setEditing:(BOOL)editing animated:(BOOL)animated

    [super setEditing:(BOOL)editing animated:(BOOL)animated];
    self.navigationItem.rightBarButtonItem.enabled = !editing;


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
    return [[self.fetchedResultsController sections] count];


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];

    int retValue = [sectionInfo numberOfObjects];

    retValue++;

    return retValue;


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:indexPath.section];

    if (indexPath.row < [sectionInfo numberOfObjects])
    
        static NSString *CellIdentifier = @"RootViewControllerClockCell";
        RootViewControllerClockCell *cell = (RootViewControllerClockCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

        if (cell == nil)
            NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"RootViewControllerClockCell" owner:nil options:nil];

            for(id currentObject in topLevelObjects)
            
                if([currentObject isKindOfClass:[RootViewControllerClockCell class]])
                
                    cell = (RootViewControllerClockCell *)currentObject;
                    break;
                
            
        

        // Configure the cell.
        NSManagedObject *managedObject = [[self.fetchedResultsController objectAtIndexPath:indexPath] retain];

        [[cell titleText] setText:[[managedObject valueForKey:@"title"] description]];

        UISwitch *mySwitch = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
        [cell addSubview:mySwitch];
        cell.accessoryView = mySwitch;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

        [mySwitch setTag:indexPath.row];

        BOOL isOn = [(NSNumber*)[managedObject valueForKey:@"active"] boolValue];

        [(UISwitch *)cell.accessoryView setOn:isOn];
        [(UISwitch *)cell.accessoryView addTarget:self action:@selector(setClockEnabled:) forControlEvents:UIControlEventValueChanged];

        [cell setEditingAccessoryType:UITableViewCellAccessoryDisclosureIndicator];

        [currentLocation release];
        [cellLocation release];
        [managedObject release];

        return cell;
    
    else 
        static NSString *CellIdentifier = @"RootViewControllerClockCellFooter";
        RootViewControllerClockCellFooter *cell = (RootViewControllerClockCellFooter*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

        if (cell == nil)
            NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"RootViewControllerClockCellFooter" owner:nil options:nil];

            for(id currentObject in topLevelObjects)
            
                if([currentObject isKindOfClass:[RootViewControllerClockCellFooter class]])
                
                    cell = (RootViewControllerClockCellFooter *)currentObject;
                    break;
                
            
        

        return cell;
    


- (NSString*)distanceToString:(double)distance

    NSString *returnString = @"";

    if (distance < 1000)
    
        returnString = [NSString stringWithFormat:@"%gm", round(distance)];
    
    else 
        returnString = [NSString stringWithFormat:@"%gkm", round(distance/1000)];
    

    return returnString;


- (void)setClockEnabled:(UISwitch*)sender

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0];

    NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
    [managedObject setValue:[NSNumber numberWithBool:sender.on] forKey:@"active"];

    NSError *error = nil;
    if (![fetchedResultsController_ performFetch:&error]) 
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    


// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:indexPath.section];

    if ((indexPath.row > [sectionInfo numberOfObjects]-1) || [self.tableView numberOfRowsInSection:indexPath.section] == 1)
        return NO;
    else
        return YES;


// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

    if (editingStyle == UITableViewCellEditingStyleDelete) 
        // Delete the managed object for the given index path
        NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
        [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];

        // Save the context.
        NSError *error = nil;
        if (![context save:&error]) 
            /*
             Replace this implementation with code to handle the error appropriately.

             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        

        if ([self.tableView numberOfRowsInSection:0] == 1)
        
            [self.tableView reloadData];
        
    


- (void)updateAlarm:(NSManagedObject*)originalAlarm withAlarm:(NSManagedObject*)newAlarm

    NSLog(@"Update!");

    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    [context deleteObject:originalAlarm];
    [context insertObject:newAlarm];

    // Save the context.
    NSError *error = nil;
    if (![context save:&error]) 
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    


- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath 
    // The table view should not be re-orderable.
    return NO;



#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
    NSLog(@"Did select row");

    if ([self.tableView isEditing])
    
        // Show editing mode
        NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];

        AddClockNavigationController *viewController = [[AddClockNavigationController alloc] initWithNibName:@"AddClockNavigationController" bundle:nil editManagedObject:managedObject];       
        [[self navigationController] presentModalViewController:viewController animated:YES];
        [viewController release];
    


- (void)cancelAddAlarmView

    [self.modalViewController dismissModalViewControllerAnimated:YES];


#pragma mark -
#pragma mark Fetched results controller

- (NSFetchedResultsController *)fetchedResultsController 

    if (fetchedResultsController_ != nil) 
        return fetchedResultsController_;
    

    /*
     Set up the fetched results controller.
     */
    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Clocks" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];

    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"addDate" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;

    [aFetchedResultsController release];
    [fetchRequest release];
    [sortDescriptor release];
    [sortDescriptors release];

    NSError *error = nil;
    if (![fetchedResultsController_ performFetch:&error]) 
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    

    return fetchedResultsController_;
    


#pragma mark -
#pragma mark Fetched results controller delegate


- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller 
    [self.tableView beginUpdates];



- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
           atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type 

    switch(type) 
        case NSFetchedResultsChangeInsert:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeDelete:
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
    



- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath 

    UITableView *tableView = self.tableView;

    switch(type) 

        case NSFetchedResultsChangeInsert:
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeDelete:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeUpdate:
            [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
            break;

        case NSFetchedResultsChangeMove:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
            break;
    



- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller 
    [self.tableView endUpdates];


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:indexPath.section];

    if (indexPath.row < [sectionInfo numberOfObjects])
    
        return 92;
    
    else 
        return 40;
    



/*
 // Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. 

 - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller 
 // In the simplest, most efficient, case, reload the table view.
 [self.tableView reloadData];
 
 */


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning 
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Relinquish ownership any cached data, images, etc that aren't in use.



- (void)viewDidUnload 
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;


- (void)dealloc 
    [fetchedResultsController_ release];
    [managedObjectContext_ release];

    [locationManager stopUpdatingLocation];
    [locationManager release];

    [super dealloc];



@end

编辑 这是保存按钮的代码,AddClockNavigationController.m

- (IBAction)saveAlarm

    [self saveTheAlarm];


- (void)saveTheAlarm

    AddClockViewController *viewController = [navigationController.viewControllers objectAtIndex:0];

    UITableView *alarmTable = viewController.theTable;

    NSIndexPath *textFieldIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    UITextField *textField = (UITextField*)[[alarmTable cellForRowAtIndexPath:textFieldIndexPath] accessoryView];

    ClockAppDelegate *appDelegate = (ClockAppDelegate*)[[UIApplication sharedApplication] delegate];

    RootViewController *parentView = [[RootViewController alloc] init];
    [appDelegate addNewAlarmWithTitle:textField.text sound:@"" recurring:[viewController hasRecurring] recurringDays:viewController.recurringDictionary];

    [parentView.tableView reloadData];
    [self.parentViewController dismissModalViewControllerAnimated:YES];

    [parentView release];

ClockAppDelegate.m

- (void)addNewAlarmWithTitle:(NSString*)alarmTitle sound:(NSString*)sound recurring:(BOOL)isRecurring recurringDays:(NSDictionary*)days

    NSManagedObjectContext *context = managedObjectContext_;
    NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"Clocks" inManagedObjectContext:context];

    [newManagedObject setValue:alarmTitle forKey:@"title"];
    [newManagedObject setValue:sound forKey:@"alarm"];
    [newManagedObject setValue:[NSNumber numberWithBool:TRUE] forKey:@"active"];
    [newManagedObject setValue:[[NSDate alloc] init] forKey:@"addDate"];

    [newManagedObject setPrimitiveValue:[NSNumber numberWithBool:isRecurring] forKey:@"recurring"];

    NSArray *myKeys = [days allKeys];
    NSArray *sortedKeys = [myKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

    for (id key in sortedKeys) 
        if ([(NSString*)[days objectForKey:key] isEqualToString:@"1"])
        
            if ([key isEqualToString:@"0"])
            
                [newManagedObject setPrimitiveValue:[NSNumber numberWithBool:TRUE] forKey:@"mon"];
            
            else if ([key isEqualToString:@"1"])
            
                [newManagedObject setPrimitiveValue:[NSNumber numberWithBool:TRUE] forKey:@"tue"];
            
            else if ([key isEqualToString:@"2"])
            
                [newManagedObject setPrimitiveValue:[NSNumber numberWithBool:TRUE] forKey:@"wed"];
            
            else if ([key isEqualToString:@"3"])
            
                [newManagedObject setPrimitiveValue:[NSNumber numberWithBool:TRUE] forKey:@"thu"];
            
            else if ([key isEqualToString:@"4"])
            
                [newManagedObject setPrimitiveValue:[NSNumber numberWithBool:TRUE] forKey:@"fri"];
            
            else if ([key isEqualToString:@"5"])
            
                [newManagedObject setPrimitiveValue:[NSNumber numberWithBool:TRUE] forKey:@"sat"];
            
            else if ([key isEqualToString:@"6"])
            
                [newManagedObject setPrimitiveValue:[NSNumber numberWithBool:TRUE] forKey:@"sun"];
            
        
    

    // Save the context.
    NSError *error = nil;
    if (![context save:&error]) 
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    

我做错了什么?

最好的问候, 保罗·皮伦

【问题讨论】:

我的第一个建议是更新现有的警报对象,而不是在编辑期间删除并创建一个新对象。 感谢您的提示。这就是我从我的 UINavigationController(由 RootViewController 打开)所做的。我不会删除并创建新警报。 你能把保存按钮后面的代码贴出来吗?如果您点击取消而不是保存,是否也会出现错误? 据我所知,点击保存按钮总是会添加一个新的“时钟”实体。话虽如此,一旦视图被关闭,NSFetchedResultsController 的内容应该将其添加到警报表中。尝试找出为什么不是。在 numberOfRowsInSection: 中放置一个断点并查看每次迭代返回的内容。另外,我在您的视频中没有看到这个 RootViewControllerClockCellFooter。找出那里发生了什么。 对不起,我添加了错误的代码。当视图以“编辑”模式打开时,它使用另一个功能。稍后会添加它。 【参考方案1】:

From Core Data Docs

托管对象无效问题: 您会看到一个异常 类似于这个例子:

[_assignObject:toPersistentStore:]: 具有 ID:#### 的 NSManagedObject 有 被作废。原因:要么你 已为故障移除了商店 您正试图开火,或者 已发送托管对象的上下文 重置消息。

补救措施:你应该放弃这个 目的。如果再次添加商店, 您可以尝试再次获取该对象

因此,基本上,您有一个对已与其存储或上下文断开连接的托管对象的引用。

我看不到发生这种情况的明显地方,但您正在向tableView:cellForRowAtIndexPath: 中的托管对象发送保留消息:

NSManagedObject *managedObject = [[self.fetchedResultsController objectAtIndexPath:indexPath] retain];

...即使您随后释放它也是危险的。永远不要保留托管对象,而是依靠上下文来保留它。否则,上下文可能会释放托管对象并将其标记为无效,而另一个对象使其保持活动状态。

我建议检查您的所有代码并找到您将保留发送到托管对象的所有位置,并删除不必要的保留/释放代码。这可能会解决问题。

如果不是,您需要检查您的持久存储是否正确分配给持久存储协调器。

【讨论】:

所以我使用了 [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];在我的代码中的各个地方,有时会删除对象并最终出现奇怪的行为 - 这可能是我的问题吧? 是的,您不想使用 mutableCopy,因为您只需要每个托管对象的一个​​活动实例。使用 mutablCopy 出现在一些 Apple 示例代码中,它被复制了,但在这种情况下使用它是不好的做法。 是的,我有一些对象数组偶尔会更改,所以我需要调整我的代码以重新获取项目。这将为我解决一些随机问题。感谢您的洞察力【参考方案2】:

我遇到了这个问题,我已经通过评论 RESET for managed object context 下面对苹果文档中的这个问题的描述进行了独奏:

您可以使用 NSManagedObjectContext 的 reset 方法删除与上下文关联的所有托管对象,并像刚刚创建它一样“重新开始”。请注意,与该上下文关联的任何托管对象都将失效,因此您需要丢弃对您仍然感兴趣的与该上下文关联的任何对象的任何引用并重新获取。

【讨论】:

以上是关于ID:[...] 的 NSManagedObject 已失效的主要内容,如果未能解决你的问题,请参考以下文章

CoreData不删除对象一对多实体

为啥 NSDate() 在 CoreData 中存储一个奇怪的值

删除时如何手动管理Core Data关系

将对象从一个 Core Data UITableView 移动到另一个?

iOS - 使用 CoreData 的 dispatch_async 保留周期

ID应用的多种办法