2013-07-22 43 views
0

我創建了一個名爲「運動員」的核心數據實體。核心數據錯誤消息

這裏是我得到的錯誤:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Athlete'' 

這是在它打破了行:

Athlete *detail = [NSEntityDescription insertNewObjectForEntityForName:@"Athlete" inManagedObjectContext:context]; 

delegate.h

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext; 
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel; 
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator; 

delegate.m

-(void)createData{ 

    NSManagedObjectContext *context = [self managedObjectContext]; 

    Athlete *detail = [NSEntityDescription insertNewObjectForEntityForName:@"Athlete" inManagedObjectContext:context]; 

    detail.first = @"Joe"; 

    detail.last = @"Pastrami"; 

    detail.phone = @"(123)456-7891"; 

    NSError *error; 

    if(![context save:&error]){ 
     NSLog(@"Error :("); 
    } 

    NSFetchRequest *request = [[NSFetchRequest alloc] init]; 

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Athlete" inManagedObjectContext:context]; 

    [request setEntity:entity]; 

    NSArray *arr = [context executeFetchRequest:request error:&error]; 

    for (Athlete *ath in arr){ 
     NSLog(@"Name %@", ath.first); 
    } 

} 



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    [self createData]; 
} 

回答

0

錯誤說明了一切:您的managedObjectContext爲零。

+0

這就是那個東西。它不應該是零。我不知道它爲什麼這麼說。 –

+0

@JosueEspinosa有時候事情並不像你認爲他們應該那樣工作。這就是堆棧跟蹤和調試有用的地方。跟蹤堆棧回到調用此方法的位置。做一些調試! – borrrden

+0

你可能想看斯坦福的CS193p視頻。老師向您演示如何使用UIManagedDocument設置Core Data存儲。一旦你明白它是如何建立的,這很簡單。 – Jamie

0

您是否正確地將您的managedObjectContext對象從AppDelegate傳遞到您的UIViewController? (在根與UINavigationController示例應用程序)

AppDelegate
  1. ::如果沒有,2種方法來做到這一點

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
        NSManagedObjectContext *context = [self managedObjectContext]; 
    
        UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController.navigationController; 
        YourViewController *yourViewController = (SearchViewController *)navigationController.topViewController; 
        yourViewController.managedObjectContext = self.managedObjectContext; 
        ... 
    } 
    
  2. YourViewController

    #import AppDelegate.h 
    ... 
    @synthesize managedObjectContext; 
    
    - (void)viewDidLoad 
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate]; 
        managedObjectContext = [appDelegate managedObjectContext]; 
        ... 
    }