2012-04-15 42 views
0

我試圖使用CLLocation Manager來獲取某人的位置,只要他們移動並將lat,lng和timestamp存儲到核心數據中,然後將其顯示在表格視圖選項卡中。然而,在控制檯輸出始終表示managedObjectContext是nill拋出此日誌coredataproject[12478:11903] After managedObjectContext: <NSManagedObjectContext: 0x7248230>爲什麼我的managedObjectContext回來了嗎?

下面是我的AppDelgate實現文件

#import "AppDelegate.h" 
#import "RootViewController.h" 
#import "FirstViewController.h" 



@implementation AppDelegate 

@synthesize window; 
@synthesize navigationController; 


#pragma mark - 
#pragma mark Application lifecycle 

- (void)applicationDidFinishLaunching:(UIApplication *)application { 

    // Configure and show the window. 

    RootViewController *rootViewController = [[RootViewController alloc] initWithStyle:UITableViewStylePlain]; 

    NSManagedObjectContext *context = [self managedObjectContext]; 
    if (!context) { 
     NSLog(@"Could not create context for self"); 
    } 
    rootViewController.managedObjectContext = context; 

    UINavigationController *aNavigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController]; 
    self.navigationController = aNavigationController; 

    [window addSubview:[navigationController view]]; 
    [window makeKeyAndVisible]; 


} 

/** 
applicationWillTerminate: saves changes in the application's managed object context before the application terminates. 
*/ 
- (void)applicationWillTerminate:(UIApplication *)application { 

    NSError *error; 
    if (managedObjectContext != nil) { 
     if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { 
      // Handle the error. 
     } 
    } 
} 

下面相關的代碼是FirstViewController.M代碼,其中我獲取位置並將其存儲在覈心數據「事件」實體

- (void)viewDidLoad 
{ 


    locationManager =[[CLLocationManager alloc] init]; 

    locationManager.delegate = self; 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
    locationManager.distanceFilter = kCLDistanceFilterNone; 
    [locationManager startUpdatingLocation]; 


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


    CLLocation *location = [locationManager location]; 
    if (!location) { 
     return; 
    } 

    /* 
    Create a new instance of the Event entity. 
    */ 
    RootViewController *rootviewcontroller = [RootViewController alloc];  
    Event *event = (Event *)[NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:rootviewcontroller.managedObjectContext]; 

    // Configure the new event with information from the location. 
    CLLocationCoordinate2D coordinate = [location coordinate]; 
    [event setLatitude:[NSNumber numberWithDouble:coordinate.latitude]]; 
    [event setLongitude:[NSNumber numberWithDouble:coordinate.longitude]]; 



    // Should be the location's timestamp, but this will be constant for simulator. 
    // [event setCreationDate:[location timestamp]]; 
    [event setTimeStamp:[NSDate date]]; 

    // Commit the change. 
    NSError *error; 

    if (![rootviewcontroller.managedObjectContext save:&error]) { 
     NSLog(@"Save Error"); 
    } 

    //RootViewController *rootviewcontroller = [RootViewController alloc]; 
    [rootviewcontroller.eventsArray insertObject:event atIndex:0]; 
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
    [rootviewcontroller.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    [rootviewcontroller.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES]; 

} 

最後這裏就是我想獲取和顯示什麼是核心數據的RootViewController的文件。這是當我點擊這個選項卡,控制檯告訴我,managedObjectConsole是nill

- (void)viewDidLoad { 

[super viewDidLoad]; 

if (managedObjectContext == nil) 
{ 
    managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
    NSLog(@"After managedObjectContext: %@", managedObjectContext); 
}  
// Set the title. 
self.title = @"Locations"; 

/* 
Fetch existing events. 
Create a fetch request; find the Event entity and assign it to the request; add a sort descriptor; then execute the fetch. 
*/ 
NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext]; 
[request setEntity:entity]; 

// Order the events by time stamp, most recent first. 
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO]; 
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; 
[request setSortDescriptors:sortDescriptors]; 


// Execute the fetch -- create a mutable copy of the result. 
NSError *error = nil; 
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; 
if (mutableFetchResults == nil) { 
    NSLog(@"Mutable Fetch Results equals nill"); 
} 

// Set self's events array to the mutable array, then clean up. 
[self setEventsArray:mutableFetchResults]; 

}

我也做了一些更多的東西與組織表中的數據,一旦它的存在,但我不認爲這就是問題所在。

我不確定爲什麼沒有在managedObjectContext中,因爲它應該有位置管理器的位置數據。我對Core數據不太熟悉,所以我可能只是在做一些簡單的錯誤,但任何洞察力都將不勝感激!

+0

爲什麼每次更新位置時都會創建一個新的RootViewController? – Felix 2012-04-15 20:46:24

+0

這只是爲了測試。當它實際開始工作時,我會將其更改爲類似20米的距離過濾器。 – michael03m 2012-04-15 21:00:10

+0

我不需要一個新的RootViewController,我只需要它通過CoreData發送一個新的位置給RootViewController。 – michael03m 2012-04-15 21:01:00

回答

1

你的錯誤在於didUpdateToLocation方法。在那裏你創建一個RootViewController的新實例。您只需要將newLocation保存到CoreData並需要該MOC(而不是RootViewController)。所以你需要找到一種方法將MOC傳遞給FirstViewController。

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

爲什麼你重置RootViewController的的MOC在viewDidLoad中:就像你在AppDelegate中或類似這樣你可以做到這一點相似?你已經通過applicationDidFinishLaunching傳遞了它!

我建議使用NSFetchedResultsController作爲表格視圖。它會自動檢測數據的變化並在需要時重新載入表格,只需正確實施委託。這裏是一個有用的教程:http://www.raywenderlich.com/999/core-data-tutorial-how-to-use-nsfetchedresultscontroller

+0

謝謝!這將使我走上正軌。 – michael03m 2012-04-15 22:27:26

相關問題