【问题标题】:Anything noticably wrong with my code?我的代码有什么明显错误吗?
【发布时间】:2011-04-28 19:51:05
【问题描述】:

在这里遇到一些有趣的错误。有什么突出的吗?具体与 MOC 和 NSFetchedResultsController 有关。我得到了一些 EXC_BAD_ACCESS 但不是特定的行,所以很难调试。

@implementation RoutineTableViewController

@synthesize routineTableView;
@synthesize entered;
@synthesize managedObjectContext;
@synthesize fetchedResultsController=__fetchedResultsController;

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    if (managedObjectContext == nil) 
    { 
        managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
    }
    [super viewDidLoad];
}

- (void)viewDidUnload
{
    self.managedObjectContext = nil;
    self.entered = nil;
    self.fetchedResultsController = nil;
    self.routineTableView = nil;
    [super viewDidUnload];
}

- (void)dealloc
{
    [__fetchedResultsController release];
    [managedObjectContext release];
    [routineTableView release];
    [entered release];
    [super dealloc];
}

#pragma mark Add an event

-(void)addRoutine
{    
    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];

    routine.name=entered;

    NSError *error = nil;
    if (![managedObjectContext save:&error]) 
    {
        // Handle the error.
    }
    NSLog(@"%@", error);

    //NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    NSInteger lastSection = [self.routineTableView numberOfSections] -1;

    [self.routineTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.routineTableView numberOfRowsInSection:lastSection]-1 inSection:lastSection] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    [routine release];
    [error release];
}

-(void)showPrompt
{
    AlertPrompt *prompt = [AlertPrompt alloc];
    prompt = [prompt initWithTitle:@"Add Workout Day" message:@"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:@"Cancel" okButtonTitle:@"Add"];
    [prompt show];
    [prompt release];
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != [alertView cancelButtonIndex])
    {
        entered = [(AlertPrompt *)alertView enteredText];

       // if(eventsArray && entered)
        {
            [self addRoutine];
        }
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    //TableViewCell *cell = (TableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

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

    Routine *tempRoutine = (Routine *)[__fetchedResultsController objectAtIndexPath:indexPath];
//    [cell setText:tempRoutine.name];
    cell.textLabel.text = tempRoutine.name;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;    
    return cell;
}


// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

-(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]];
         NSLog(@"fetched results : \n%@\n",[self.fetchedResultsController fetchedObjects]);

         // Commit the change.
         NSError *error = nil;

         // Update the array and table view.
         if (![managedObjectContext save:&error]) 
         {
             // Handle the error.
         }
         //[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
     }
 }

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = [[managedObject valueForKey:@"name"] description];
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

     RoutineDayTableViewController *detailViewController = [[RoutineDayTableViewController alloc] initWithNibName:@"RoutineDayTableViewController" bundle:nil];
    NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];

    detailViewController.title = [[managedObject valueForKey:@"name"] description];
//
//    // Pass the selected object to the new view controller.
//     [self.navigationController pushViewController:detailViewController animated:YES];
//     [detailViewController release];

    detailViewController.theSelectedRoutine = [__fetchedResultsController objectAtIndexPath: indexPath];
    NSLog(@"detailViewController.theSelectedRoutine:%@",detailViewController.theSelectedRoutine);
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}

#pragma mark - Fetched results controller

- (NSFetchedResultsController *)fetchedResultsController
{
    if (__fetchedResultsController != nil)
    {
        return __fetchedResultsController;
    }

    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Routine" 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:@"name" 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:nil];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;

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

    NSError *error = nil;
    if (![self.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 - Fetched results controller delegate


- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
    [self.routineTableView beginUpdates];
}

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
           atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
    switch(type)
    {
        case NSFetchedResultsChangeInsert:
            [self.routineTableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeDelete:
            [self.routineTableView 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.routineTableView;

    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.routineTableView endUpdates];
}
@end

编辑:这里是应用程序 delegate.m

@implementation AppDelegate

@synthesize window=_window;
@synthesize rootController;
@synthesize excerciseNavController;
@synthesize managedObjectContext=__managedObjectContext;

@synthesize managedObjectModel=__managedObjectModel;

@synthesize persistentStoreCoordinator=__persistentStoreCoordinator;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [self.window addSubview:rootController.view];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}
- (void)dealloc
{
    [_window release];
    [rootController release];
    [excerciseNavController release];
    [__managedObjectContext release];
    [__managedObjectModel release];
    [__persistentStoreCoordinator release];
    [super dealloc];
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil)
    {
        if ([managedObjectContext hasChanges] && ![managedObjectContext 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();
        } 
    }
}

#pragma mark - Core Data stack

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *)managedObjectContext
{
    if (__managedObjectContext != nil)
    {
        return __managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil)
    {
        __managedObjectContext = [[NSManagedObjectContext alloc] init];
        [__managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return __managedObjectContext;
}

/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created from the application's model.
 */
- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil)
    {
        return __managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Temp" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];    
    return __managedObjectModel;
}


/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil)
    {
        return __persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Temp.sqlite"];

    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&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.

         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.


         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
         [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    

    return __persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}


@end

【问题讨论】:

  • 您能告诉我们这些错误是什么吗?
  • 您发布的代码很长,您的问题太宽泛,请更具体。
  • 谢谢大家,我刚刚删除了不相关的代码。我刚刚在if (![managedObjectContext save:&amp;error]) 遇到崩溃 EXC BAD ACCESS。这段代码与我在这里的代码有关,所以我试图查明发生了什么。 stackoverflow.com/questions/5815549/…
  • 您是否删除了您的应用并重新安装了它?有时 CoreData 会损坏。
  • @Pier,是的,我已经完成了清理工作,并重置了模拟器并删除并重新安装,但仍然有问题。

标签: iphone objective-c core-data


【解决方案1】:

如果你有一个 EXEC_BAD_ACCESS,你应该打开僵尸并重新运行你的应用,这样你就可以看到过度释放的内容;

http://developer.apple.com/library/ios/#documentation/Xcode/Conceptual/iphone_development/130-Debugging_Applications/debugging_applications.html

一旦您了解了过度发布的内容,您就会更好地了解正在发生的事情。

【讨论】:

    【解决方案2】:

    当您将值分配给 managedObjectContext - 尝试执行以下任一操作:

    managedObjectContext = [[(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext] retain];
    

    或者,如果您的 managedObjectContext 属性在其定义中有保留,您可以尝试

    self.managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
    

    【讨论】:

    • 现在在应用程序的 main.m 中出现 EXC_BAD_ACCESS 错误。问题出在这个类(父类)或子类(stackoverflow.com/questions/5815549/…)。
    • 你的 CurlAppDelegate 是什么样子的。当您在那里创建 managedObjectContext 时 - 您保留它吗?此外,您是否在创建 managedObjectContext 之前加载您的视图。一旦在 UIViewController 上引用了 .view,就会调用 loadView。
    • 谢谢布赖恩。我已将我的应用委托添加到问题中。
    【解决方案3】:

    我想知道 managedObjectContext 是否会因为你没有保留它而从你手下被释放?

    在你的 viewDidLoad 中试试这个,看看是否有什么不同:

    if (managedObjectContext == nil) 
    { 
        self.managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
    }
    

    【讨论】:

      【解决方案4】:

      这有点让我害怕......你会返回一个 nil MOC,一个 MOC 可能永远不会被分配

      if (__managedObjectContext != nil)
      {
          return __managedObjectContext;
      }
      
      NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
      if (coordinator != nil)
      {
          __managedObjectContext = [[NSManagedObjectContext alloc] init];
          [__managedObjectContext setPersistentStoreCoordinator:coordinator];
      }
      return __managedObjectContext;
      

      你为什么不在你的应用委托中做这个,做一次。

      也许做一些类似的事情:

      if (__managedObjectContext != nil)
      {
          return __managedObjectContext;
      }
      __managedObjectContex = [[NSManagedObjectContext alloc] init];
      
      
      NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
      if (coordinator != nil)
      {
          //__managedObjectContext = [[NSManagedObjectContext alloc] init];
          [__managedObjectContext setPersistentStoreCoordinator:coordinator];
      }
      return __managedObjectContext;
      

      【讨论】:

      • 如果 [self persistentStoreCoordinator] 为 nil,仍然没有解决分配协调器的问题。
      • 感谢 Grady,我现在解决了这个问题。它可能在将来为我节省了一些麻烦,但不幸的是并没有解决我遇到的崩溃问题。我认为此时我最好的选择是尝试僵尸,看看我是否能找出发生了什么。
      • 是的,你通常应该在开发时启用僵尸,除非你会占用大量内存,或者你正在检查泄漏、性能等。请记住,使用僵尸开,如果您没有收到“发送到已释放对象的消息”...错误,它们可能一开始就没有分配/初始化。
      【解决方案5】:

      您确实需要在代码中的任何地方使用self.propertyName 引用表单,除了该特定属性的访问器中。

      例如:entered 是属性,但在代码中无处不在,即使您设置了值,您也只使用不保留任何内容的直接访问形式。例如,

      entered = [(AlertPrompt *)alertView enteredText];
      

      由于alertView 几乎肯定会返回一个自动释放的 NSString 对象,因此该对象将在下次自动释放池耗尽时消失而不会发出警告。你永远不会时时刻刻知道entered 是否有价值。

      你真的,真的,真的需要使用:

      self.entered = [(AlertPrompt *)alertView enteredText];
      

      ... 以确保保留该值。

      【讨论】:

        猜你喜欢
        • 2021-05-07
        • 2022-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多