2015-02-23 52 views
-1

我目前正在使用CoreData並試圖使用NSFetchedResultsController獲取數據。 但應用程序崩潰在下面的行- [__ NSArrayM objectAtIndex:]:索引9超出空數組的邊界'

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 


#the app crashes here 
id sectionInfo = [[self.fetchedRequestController sections]objectAtIndex:section]; 


    return [sectionInfo numberOfObjects]; 

} 

與錯誤消息:- [__ NSArrayM objectAtIndex:]:索引9超出界限爲空數組」

在你告訴我數組是空的之前,我知道但如何填充它呢? 我不知道我錯在哪裏,其他問題都無法提供幫助。

AppDelgate.m只是從核心數據預置複製和粘貼。 以防萬一它的事項:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 

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:. 
// Saves changes in the application's managed object context before the application terminates. 
[self saveContext]; 
} 

#pragma mark - Core Data stack 


- (NSURL *)applicationDocumentsDirectory { 
// The directory the application uses to store the Core Data store file. This code uses a directory named "controwl.a" in the application's documents directory. 
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 
} 

- (NSManagedObjectModel *)managedObjectModel { 
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model. 
if (_managedObjectModel != nil) { 
    return _managedObjectModel; 
} 
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"trackingData" withExtension:@"momd"]; 
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; 
return _managedObjectModel; 
} 

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. 
if (_persistentStoreCoordinator != nil) { 
    return _persistentStoreCoordinator; 
} 

// Create the coordinator and store 

_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"timetracking.sqlite"]; 
NSError *error = nil; 
NSString *failureReason = @"There was an error creating or loading the application's saved data."; 
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { 
    // Report any error we got. 
    NSMutableDictionary *dict = [NSMutableDictionary dictionary]; 
    dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data"; 
    dict[NSLocalizedFailureReasonErrorKey] = failureReason; 
    dict[NSUnderlyingErrorKey] = error; 
    error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict]; 
    // Replace this 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. 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    abort(); 
} 

return _persistentStoreCoordinator; 
} 


- (NSManagedObjectContext *)managedObjectContext { 
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) 
if (_managedObjectContext != nil) { 
    return _managedObjectContext; 
} 

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

#pragma mark - Core Data Saving support 

- (void)saveContext { 
NSManagedObjectContext *managedObjectContext = self.managedObjectContext; 
if (managedObjectContext != nil) { 
    NSError *error = 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. 
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
     abort(); 
    } 
} 
} 

@end 

而且TableViewClass其中fetchedResultsController被調用。

#import "FirstTableViewController.h" 

@interface FirstTableViewController() 

@end 

@implementation FirstTableViewController 
@synthesize fetchedRequestController = _fetchedRequestController; 
@synthesize managedObjectContext = _managedObjectContext; 

- (void)viewDidLoad { 
[super viewDidLoad]; 

NSError *error; 
if (![[self fetchedRequestController]performFetch:&error]) { 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    exit(-1); 
} 

self.title = @"Customer Names"; 


_managedObjectContext = [(AppDelegate*)[[UIApplication sharedApplication]delegate] managedObjectContext]; 



NSManagedObject* customer; 

customer = [NSEntityDescription insertNewObjectForEntityForName:@"Customer" inManagedObjectContext:_managedObjectContext]; 



} 

- (void)didReceiveMemoryWarning { 
[super didReceiveMemoryWarning]; 
// Dispose of any resources that can be recreated. 
} 

- (NSFetchedResultsController *)fetchedRequestController { 
if (_fetchedRequestController != nil) { 
    return _fetchedRequestController; 
} 

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Customer" inManagedObjectContext:_managedObjectContext]; 
[fetchRequest setEntity:entity]; 

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO]; 
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]]; 

[fetchRequest setFetchBatchSize:20]; 

NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_managedObjectContext sectionNameKeyPath:@"nam" cacheName:@"Root"]; 


self.fetchedRequestController = theFetchedResultsController; 
_fetchedRequestController.delegate = self; 


return _fetchedRequestController; 

} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

    id sectionInfo = [[self.fetchedRequestController sections]objectAtIndex:section]; 
    return [sectionInfo numberOfObjects]; 

} 

- (void)configureCell:(UITableViewCell*)cell atIndexPath:(NSIndexPath *)indexPath { 
UIViewController *customer = [_fetchedRequestController objectAtIndexPath:indexPath]; 
cell.textLabel.text = @"test"; 
} 
#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
#warning Potentially incomplete method implementation. 
// Return the number of sections. 
return 10; 
} 


- (void)viewDidUnload { 
    self.fetchedRequestController = nil; 
} 
@end 

回答

0

您的numberOfSectionsInTableView:的實施說,有10個部分。你的崩潰告訴你的是,這是不正確的。表格視圖詢問委託人應該有多少部分,然後詢問每個部分的細節。如果返回錯誤數量的部分,表格視圖會詢問不存在部分的詳細信息。

你不應該硬編碼段的數量。NSFetchedResultsController的文檔提供了一個可能需要的示例實現:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return [self.fetchedRequestController sections] count]; 
} 
相關問題