为什么我的managedObjectContext回来了?

时间:2012-04-15 20:13:37

标签: iphone objective-c core-data cllocationmanager

我正在尝试使用CLLocation Manager来移动某个人的位置并将lat,lng和timestamp存储到核心数据中,然后在表格视图选项卡中显示该位置。但是,控制台中的输出始终通过抛出此日志coredataproject[12478:11903] After managedObjectContext: <NSManagedObjectContext: 0x7248230>

来指示managedObjectContext为nill

以下是我的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中没有任何内容,因为它应该具有来自位置管理器的位置数据。我对核心数据不太熟悉,所以我可能只是做了一些简单的错误,但任何见解都会受到赞赏!

1 个答案:

答案 0 :(得分:1)

你的错误在于didUpdateToLocation方法。在那里,您创建了一个RootViewController的新实例。您只需要将newLocation保存到CoreData并需要MOC(而不是RootViewController)。所以你需要找到一种方法将MOC传递给FirstViewController。您可以像在AppDelegate中那样执行此操作,或者像这样:

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

为什么要在viewDidLoad中重置RootViewController的MOC?你已经在applicationDidFinishLaunching中传递了它!

我建议在表格视图中使用NSFetchedResultsController。它会自动检测数据的更改并在需要时重新加载表,只需正确实现委托即可。这是一个有用的教程:http://www.raywenderlich.com/999/core-data-tutorial-how-to-use-nsfetchedresultscontroller