Ios entityForName:无问题

Ios entityForName:无问题,ios,core-data,Ios,Core Data,我正在尝试使用核心数据,让用户可以添加最喜欢的汽车。用户可以选择单独的tableviewcontroller、modela文本字段和yeara文本字段中的Make。汽车将显示在桌面视图上。 我认为我正确地实现了CoreData,但由于未捕获的异常“NSInvalidArgumentException”,我正在终止应用程序,原因:“+entityForName:nil不是合法的NSManagedObjectContext。我不知道是什么导致我的managedObjectContent等于零 这是第

我正在尝试使用核心数据,让用户可以添加最喜欢的汽车。用户可以选择单独的tableviewcontroller、modela文本字段和yeara文本字段中的Make。汽车将显示在桌面视图上。 我认为我正确地实现了CoreData,但由于未捕获的异常“NSInvalidArgumentException”,我正在终止应用程序,原因:“+entityForName:nil不是合法的NSManagedObjectContext。我不知道是什么导致我的managedObjectContent等于零

这是第一个视图。这将显示喜爱的汽车阵列

#import "addCar.h"
#import "dreamCar.h"

@implementation dreamCar
@synthesize dreamCarArray;

// Retrieve managed object context and later save the data
-(NSManagedObjectContext *)managedObjectContext{
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if([delegate performSelector:@selector(managedObjectContext)]){
        context = [delegate managedObjectContext];
    }
    return context;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    // Get cars from database
    NSManagedObjectContext *moc = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"Cars"];
    dreamCarArray = [[moc executeFetchRequest:fetchRequest error:nil]mutableCopy];

    [self.tableView reloadData];
}


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

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   return dreamCarArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:      (NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"dreamCarCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier    forIndexPath:indexPath];

// Configure the cell
NSManagedObject *car = [dreamCarArray objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:@"%@ %@ %@", [car  valueForKey:@"year"],[car valueForKey:@"make"],[car valueForKey:@"model"]]];

 return cell;
}

@end
下面是用户可以添加汽车的下一个视图:

#import "addCar.h"
#import "addDreamCarMake.h"

@implementation addCar
@synthesize makeText,modelText,yearText,car;

// Retrieve managed object context and later save the data
-(NSManagedObjectContext *)managedObjectContext{
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if([delegate performSelector:@selector(managedObjectContext)]){
       context = [delegate managedObjectContext];
    }
    return context;
}


-(void)viewDidLoad{
    [super viewDidLoad];

    self.modelText.delegate = self;
    self.yearText.delegate = self;

    if(car){
        [self.makeText setText:[car valueForKey:@"make"]];
        [self.modelText setText:[car valueForKey:@"model"]];
        [self.yearText setText:[car valueForKey:@"year"]];
    }
}

//If cancel button is pressed, pop current view from stack
- (IBAction)cancelButtonPressed:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

// If done button is pressed
- (IBAction)doneButtonPressed:(id)sender {
     NSManagedObjectContext *context = [self managedObjectContext];

    // Create new Car
    NSManagedObject *newCar = [NSEntityDescription insertNewObjectForEntityForName:@"Cars" inManagedObjectContext:context];
    [newCar setValue:makeText forKey:@"make"];
    [newCar setValue:modelText forKey:@"model"];
    [newCar setValue:yearText forKey:@"year"];

    //Pop current view from stack
    [self.navigationController popToRootViewControllerAnimated:YES];
}

// Unwind segue from addDreamCarMake
- (IBAction)unwindToListFromAddMake:(UIStoryboardSegue *)segue{
    addDreamCarMake *segue1 = segue.sourceViewController;
    self.makeText.text = segue1.makeName;
}

//Dismiss Keyboard
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [self.modelText resignFirstResponder];
    [self.yearText resignFirstResponder];
}

// Dismiss Keyboard
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if(textField){
        [textField resignFirstResponder];
    }
    return NO;
}
@end
以下是用于选择品牌的表格视图:

#import "addCar.h"  
#import "addDreamCarMake.h"

static NSString* makeLabel;

@implementation addDreamCarMake
@synthesize makeName;

- (void)viewDidLoad
{
    [super viewDidLoad];

     //Initial Dictionary
makes = @{ @"A" : @[@"Acura",
                     @"AJS",
                     @"Alfa Romeo",
                     @"Allard",
                     @"Allis Chalmers",
                     @"AM General",
                     @"AMC",
                     @"American",
                     @"American Motors",
                     @"Amphicar",
                     @"Ancarrow",
                     @"Ariel",
                     @"Arnolt",
                     @"Arnolt Bristol",
                     @"Art Work",
                     @"Assembled",
                     @"Aston Martin",
                     @"ASVE",
                     @"ASVE",
                     @"Auburn",
                     @"Audi",
                     @"Aurora",
                     @"Austin",
                     @"Austin-Healey",
                     @"Avanti",],
            @"B" : @[@"Bay Marine",
                     @"Beck",
                     @"Bentley",
                     @"BMW",
                     @"Borum",
                     @"Boss",
                     @"Bourget",
                     @"Brainerd Robbins",
                     @"Bricklin",
                     @"BSA",
                     @"Bugatti",
                     @"Buick",],
            @"C" : @[@"C Boat",
                     @"Cadillac",
                     @"Callaway",
                     @"Caterpillar",
                     @"CAV",
                     @"Century",
                     @"Checker",
                     @"Chevrolet",
                     @"Chris-Craft",
                     @"Chris-Craft/Dewhurst",
                     @"Chrysler",
                     @"Cobra",
                     @"Concept",
                     @"Condor",
                     @"Cord",
                     @"Crosley",
                     @"Cushman",
                     @"Custom",
                     @"Custom Built",
                     @"CZ",],
            @"D" : @[@"Daewoo",
                     @"Daihatsu",
                     @"Daimler",
                     @"Dan Kidney",
                     @"Datsun",
                     @"Delorean",
                     @"DeSoto",
                     @"DeTomaso",
                     @"Diamond",
                     @"Dingle",
                     @"DKW",
                     @"Dodge",
                     @"Dodge ",
                     @"Dry Lakes",
                     @"Duck Boat",
                     @"Duesenberg",
                     @"Dunphy",
                     @"Dyno",],
            @"E" : @[@"Eagle",
                     @"Eddie Trotta",
                     @"Edmunds-Kenyon",
                     @"Edsel",
                     @"Era",
                     @"Essex",
                     @"Evinrude",
                     @"Excalibur",
                     @"Eysink",],
            @"F" : @[@"Factory Five",
                     @"Fantasy",
                     @"Farmall",
                     @"Ferrari",
                     @"Fiat",
                     @"Fleetwood",
                     @"Ford",
                     @"Forsa",
                     @"Framed Art",
                     @"Franklin",
                     @"Frazer",],
            @"G" : @[@"Gar Wood",
                     @"Gar Wood/Michaud",
                     @"Gasoline Pump",
                     @"Geo",
                     @"Glen-L",
                     @"GM",
                     @"GMC",
                     @"Goodhue & Hawkins",
                     @"Graham",
                     @"Greavette",
                     @"Griffith",],
            @"H" : @[@"Hacker",
                     @"Hackercraft",
                     @"Harley-Davidson",
                     @"Hendrick Motorsports",
                     @"Henry J",
                     @"Hickman",
                     @"Higgins ",
                     @"Hillman",
                     @"Hogzoom",
                     @"Holden",
                     @"Honda",
                     @"Horex",
                     @"Hudson",
                     @"Hummer",
                     @"Hunter",
                     @"Hupmobile",
                     @"Hutchinson",
                     @"Hyundai",],
            @"I" : @[@"IH",
                     @"IH Farmall",
                     @"Imperial",
                     @"Indian",
                     @"Indian Lakes",
                     @"Infiniti",
                     @"International",
                     @"Isotta",
                     @"Isuzu",],
            @"J" : @[@"Jaguar",
                     @"JBL",
                     @"Jeep",
                     @"Jensen",
                     @"John Deere",
                     @"Johnson",],
            @"K" : @[@"Kaiser",
                     @"Kia",
                     @"KR Proton",
                     @"Kurtis",],
            @"L" : @[@"Lagonda",
                     @"Lamborghini",
                     @"Land Rover",
                     @"Larson",
                     @"Lasalle",
                     @"Lexus",
                     @"Lighted Sign",
                     @"Lincoln",
                     @"Lola",
                     @"Lotus",
                     @"Lucky Fire",
                     @"Luyere",
                     @"Lyman",],
            @"M" : @[@"MAC Tools",
                     @"Mack",
                     @"Malibu",
                     @"Maserati",
                     @"Massey-Harris",
                     @"Matchless",
                     @"Maxton",
                     @"Mazda",
                     @"McCormick",
                     @"McLaren",
                     @"Memorabilia",
                     @"Mercedes-Benz",
                     @"Mercury",
                     @"Merkur",
                     @"Metal Sign",
                     @"MG",
                     @"Midget",
                     @"Mini",
                     @"Mitsubishi",
                     @"Model",
                     @"Moore",
                     @"Morris",
                     @"Mugen",
                     @"Murray",
                     @"MV Agusta",],
            @"N" : @[@"N.U.T.",
                     @"Nash",
                     @"Neon Sign",
                     @"Nissan",
                     @"Norton",
                     @"NSU",],
            @"O" : @[@"Oakland",
                     @"OCC",
                     @"Oldsmobile",
                     @"Oliver Hart-Parr",],
            @"P" : @[@"Pabst ",
                     @"Pace Arrow",
                     @"Packard",
                     @"Panoz",
                     @"Panther",
                     @"Parts",
                     @"Penn Yan",
                     @"Peugeot",
                     @"Pierce-Arrow",
                     @"Plastic Sign",
                     @"Plymouth",
                     @"Pontiac",
                     @"Porcelain Sign",
                     @"Porsche",
                     @"Prevost",
                     @"Pulse",],
            @"Q" : @[@"Qvale",],
            @"R" : @[@"Racing ",
                     @"Rambler",
                     @"Reading-Standard",
                     @"Renault",
                     @"Reo",
                     @"Replica",
                     @"Replicar",
                     @"Retrovette",
                     @"Revcon",
                     @"Richardson",
                     @"Riva",
                     @"Rolls-Royce",],
            @"S" : @[@"Saab",
                     @"Saleen",
                     @"Saturn",
                     @"Schwinn",
                     @"Scorpion",
                     @"Sea Lyon",
                     @"Seagrave",
                     @"Shay",
                     @"Shelby",
                     @"Shepherd",
                     @"SIMCA",
                     @"Sims",
                     @"Skiff Craft",
                     @"Speed Sport",
                     @"Star",
                     @"Staudacher",
                     @"Sterling",
                     @"Steve McQueen",
                     @"Steyr-Daimler Puch",
                     @"Stone Boatyard",
                     @"Studebaker",
                     @"Subaru",
                     @"Sudlow",
                     @"Sunbeam",
                     @"Sunflower",
                     @"Superformance",
                     @"Suzuki",],
            @"T" : @[@"Thompson",
                     @"Tidal Force",
                     @"Tiffany",
                     @"Tin Sign",
                     @"Toyota",
                     @"Trigre",
                     @"Triumph",
                     @"Truscott",
                     @"TVR",],
            @"V" : @[@"Ventnor",
                     @"Vincent",
                     @"Volkswagen",
                     @"Volvo",],
            @"W" : @[@"Wagner",
                     @"Westcott",
                     @"Whiticar",
                     @"Whizzer",
                     @"Willys",
                     @"Wise & Sons",
                     @"Wise Boat & Bus Works",],
            @"Y" : @[@"Yamaha",
                     @"Yamaha Castrol",
                     @"Yellow Jacket",],
            @"Z" : @[@"Zimmer",
                     @"Zundapp",]},

     makeSectionTitles = [[makes allKeys]   sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [makeSectionTitles count];
}

// Title at each section
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [makeSectionTitles objectAtIndex:section];
}

// Number of rows
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    NSString *sectionTitle = [makeSectionTitles objectAtIndex:section];
    NSArray *sectionModels = [makes objectForKey:sectionTitle];
    return [sectionModels count];
}

// Item at each cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addDreamCarMakeCell" forIndexPath:indexPath];

    // Configure the cell...
    NSString *sectionTitle = [makeSectionTitles objectAtIndex:indexPath.section];
    NSArray *sectionmodels = [makes objectForKey:sectionTitle];
    NSString *model = [sectionmodels objectAtIndex:indexPath.row];
    cell.textLabel.text = model;

    return cell;
}

// Index on the left side
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return makeSectionTitles;
}

// If back button is pressed, pop current view from stack
- (IBAction)backButtonPressed:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}


// Segue
-(void) prepareForSegue: (UIStoryboardSegue *)segue sender: (UITableViewCell *)sender {

    //Segue back to searchCar
    if ([segue.identifier isEqualToString:@"addMakeCompleted"]) {
    makeLabel = sender.textLabel.text;
    self.makeName = makeLabel;
    }
}
@end
这是appdelegate.h

#import <UIKit/UIKit.h>

@interface infoMobileAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (weak, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (weak, nonatomic) NSManagedObjectContext *managedObjectModel;
@property (weak, nonatomic) NSManagedObjectContext *persistentStoreCoordinator;

@end
编辑: 因此,在我的addCar.h中,我添加了一个名为car的NSManagedObject。强的,非原子的 在我的addCar.m中,当我通过viewdiload进行调试时,我看到它跳过了ifcar语句。我想这就是导致零的原因

-(void)viewDidLoad{
    [super viewDidLoad];

    self.modelText.delegate = self;
    self.yearText.delegate = self;

    if(car){
        [self.makeText setText:[car valueForKey:@"make"]];
        [self.modelText setText:[car valueForKey:@"model"]];
        [self.yearText setText:[car valueForKey:@"year"]];
    }
}
再次编辑: 修好了。我的应用程序委托缺少一些方法。以下是我必须添加的方法,以防有人想知道:

- (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.
            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:@"coreDataInfoNet" 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:@"coreDataInfoNet.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.

         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:
         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}

         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

检查你的应用程序代理,他们需要一些核心数据方法,如果编码不正确,可能导致MOC为零:

  #pragma mark - Core Data stack

  - (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. 
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        exit(-1);
     } 
  }
  }



- (NSManagedObjectContext *)managedObjectContext   {

    if (__managedObjectContext != nil)
     {
      return __managedObjectContext;       }

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

  }

- (NSManagedObjectModel *)managedObjectModel
{
  if (__managedObjectModel != nil)
  {
    return __managedObjectModel;
}
      NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"QRData" withExtension:@"momd"];

    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
  return __managedObjectModel;
}


- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
    return __persistentStoreCoordinator;
}

  NSURL *storeURL = [[self applicationDocumentsDirectory]    
URLByAppendingPathComponent:@"QRU.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. 

     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]);
    exit(-1);
  }    

  return __persistentStoreCoordinator;
}

检查你的应用程序代理,他们需要一些核心数据方法,如果编码不正确,可能导致MOC为零:

  #pragma mark - Core Data stack

  - (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. 
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        exit(-1);
     } 
  }
  }



- (NSManagedObjectContext *)managedObjectContext   {

    if (__managedObjectContext != nil)
     {
      return __managedObjectContext;       }

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

  }

- (NSManagedObjectModel *)managedObjectModel
{
  if (__managedObjectModel != nil)
  {
    return __managedObjectModel;
}
      NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"QRData" withExtension:@"momd"];

    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
  return __managedObjectModel;
}


- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
    return __persistentStoreCoordinator;
}

  NSURL *storeURL = [[self applicationDocumentsDirectory]    
URLByAppendingPathComponent:@"QRU.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. 

     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]);
    exit(-1);
  }    

  return __persistentStoreCoordinator;
}
放弃视图控制器中的if语句怎么样

如果您使用空的应用程序模板启动一个新的Xcode项目,并单击使用核心数据复选框,您将在应用程序委托中看到所需的代码

配置PersistentStoreCoordinator 加载ManagedObjectModel 打开ManagedObjectContext 默认项目模板在AppDelegate上将这些作为属性公开,因此您可以像这样引用应用程序中其他地方的属性

// note that you need to import the header to see the properties directly
#import "AppDelegate.h"

AppDelegate *myApp = [UIApplication sharedApplication];
NSManagedObjectContext *moc = myApp.managedObjectContext;
// use the moc as required....
这样做的好处是,您只有一个方法正在设置ManagedObjectContext,因此,如果它的行为不符合预期,那么只有一个地方可以查看。。。无需将moc设置为nil,然后根据if语句将其设置为非nil值

希望有帮助。

放弃视图控制器中的if语句怎么样

如果您使用空的应用程序模板启动一个新的Xcode项目,并单击使用核心数据复选框,您将在应用程序委托中看到所需的代码

配置PersistentStoreCoordinator 加载ManagedObjectModel 打开ManagedObjectContext 默认项目模板在AppDelegate上将这些作为属性公开,因此您可以像这样引用应用程序中其他地方的属性

// note that you need to import the header to see the properties directly
#import "AppDelegate.h"

AppDelegate *myApp = [UIApplication sharedApplication];
NSManagedObjectContext *moc = myApp.managedObjectContext;
// use the moc as required....
这样做的好处是,您只有一个方法正在设置ManagedObjectContext,因此,如果它的行为不符合预期,那么只有一个地方可以查看。。。无需将moc设置为nil,然后根据if语句将其设置为非nil值


希望这有帮助。

确保上下文不为空,并在视图控制器的managedObjectContext方法中设置断点,顺便说一句,这看起来有点太复杂了。然后逐步检查您的程序,并检查上下文未按预期返回的原因。此外,我强烈建议您不要在核心数据上打喷嚏。还要确保您没有拼写错误实体名称,并通过设置断点调试您的程序。我还建议切换到使用队列限制和父子关系上下文而不是线程限制。线程限制是一种传统的处理方式,即使苹果的模板和示例仍然使用这种方式。请确保上下文不要在视图控制器的managedObjectContext方法中设置断点,顺便说一句,这看起来有点太复杂了。然后逐步检查您的程序,并检查上下文未按预期返回的原因。此外,我强烈建议您不要在核心数据上打喷嚏。还要确保您没有拼写错误实体名称,并通过设置断点调试您的程序。我还建议切换到使用队列限制和父子关系上下文而不是线程限制。线程限制是做事情的传统方式,即使苹果的模板和示例仍然使用它。这实际上是一个非常糟糕的例子。您不应该将此类内容转储到应用程序代理中并以这种方式访问它们。Apple的模板将该上下文从应用程序委托传递到视图控制器。从视图控制器的委托获取托管对象上下文也是一种有效的方法。也许我误解了,但我认为如果OP知道如何设置符号断点并调试问题,他或她应该已经这样做了。我并不是说这是唯一正确的方法;我的意思是,这是一个预兆,可以让OP通过这个问题。我们都必须先写一堆糟糕的代码,然后才能写出好代码;这是一段让他或她继续前进的错误代码
这实际上是一个非常糟糕的例子。您不应该将此类内容转储到应用程序代理中并以这种方式访问它们。Apple的模板将该上下文从应用程序委托传递到视图控制器。从视图控制器的委托获取托管对象上下文也是一种有效的方法。也许我误解了,但我认为如果OP知道如何设置符号断点并调试问题,他或她应该已经这样做了。我并不是说这是唯一正确的方法;我的意思是,这是一个预兆,可以让OP通过这个问题。我们都必须先写一堆糟糕的代码,然后才能写出好代码;这是一段糟糕的代码,会让他或她进入下一个挑战。应用程序代理不需要提供这些。任何东西都可以提供托管对象上下文、持久存储协调器或持久存储。@quellish你疯了,你的意思是核心数据内容可能在应用程序委托中,也可能不在应用程序委托中,但它存在是有原因的,这是为了确保每次应用程序放弃控制时都可以保存MOC。-voidapplicationWillResignActive:UIApplication*应用程序{[self-saveContext];}-voidApplicationIdentinterBackground:UIApplication*应用程序{[self-saveContext];}。。。您将如何确保保存MOC?托管对象上下文是更改的草稿。保存或放弃它的时间取决于您或您的用户。您的视图控制器可以轻松地保存在VIEWWILLOVISAR:,或侦听与应用程序委托相同的通知。应用程序委托不是示例UIApplicationWillResignActivification中可以处理的唯一位置。但应用程序委托是最方便的位置,可确保在放弃控制时始终保存它,特别是当您在所有位置都有核心数据访问权限时-否则您会丢失更改,这是一个很大的原因,这些代码是模板的一部分,当你开始一个新的应用程序的核心数据。我不是说你所说的不是真的,我是说你所做的标记好的答案是错误的。更不用说你可能吓到了问这个问题的新手。只有当你不正确地使用核心数据时才会这样。您应该为每一组更改创建一个新的上下文。您正在讨论的模板在应用程序委托中创建核心数据堆栈,但它们将上下文传递给视图控制器。苹果自己的文档对此很清楚:嵌套上下文比以往任何时候都更重要,你可以采用“传递接力棒”的方法,通过将上下文从一个视图控制器传递到下一个视图控制器来访问上下文,而不是直接从应用程序委托检索上下文。来自iOS 5的新增功能。不需要应用程序委托来提供这些功能。任何东西都可以提供托管对象上下文、持久存储协调器或持久存储。@quellish你疯了,你的意思是核心数据内容可能在应用程序委托中,也可能不在应用程序委托中,但它存在是有原因的,这是为了确保每次应用程序放弃控制时都可以保存MOC。-voidapplicationWillResignActive:UIApplication*应用程序{[self-saveContext];}-voidApplicationIdentinterBackground:UIApplication*应用程序{[self-saveContext];}。。。您将如何确保保存MOC?托管对象上下文是更改的草稿。保存或放弃它的时间取决于您或您的用户。您的视图控制器可以轻松地保存在VIEWWILLOVISAR:,或侦听与应用程序委托相同的通知。应用程序委托不是示例UIApplicationWillResignActivification中可以处理的唯一位置。但应用程序委托是最方便的位置,可确保在放弃控制时始终保存它,特别是当您在所有位置都有核心数据访问权限时-否则您会丢失更改,这是一个很大的原因,这些代码是模板的一部分,当你开始一个新的应用程序的核心数据。我不是说你所说的不是真的,我是说你所做的标记好的答案是错误的。更不用说你可能吓到了问这个问题的新手。只有当你不正确地使用核心数据时才会这样。您应该为每一组更改创建一个新的上下文。您正在讨论的模板在应用程序委托中创建核心数据堆栈,但它们将上下文传递给视图控制器。苹果自己的文档对此很清楚:嵌套上下文比以往任何时候都更重要,你可以采用“传递接力棒”的方法,通过将上下文从一个视图控制器传递到下一个视图控制器来访问上下文,而不是直接从应用程序委托检索上下文。来自iOS 5的新功能。