0

Я пытаюсь использовать подконтекст, поэтому я могу использовать подкласс NSManagedObject как обычный класс, чтобы просто хранить информацию. Как блокнот ...Детский контекст новый управляемый объект

Цель: NSManagedObject

+ (Target*)initWithCoreData{ 

NSManagedObjectContext * context = [[CoreDataWrapper sharedInstance] childManagedObjectContext]; 

NSEntityDescription * ent= [NSEntityDescription insertNewObjectForEntityForName:@"Target" 
               inManagedObjectContext:context]; 

Target * target = [[Target alloc] initWithEntity:ent insertIntoManagedObjectContext:context]; 

return target; 
} 

Прагма знак - Core Data

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

/** 
* Create ManagedObjectModel if it doesn't exist already 
* 
* @return ManagedObjectModel used with CoreData 
*/ 
- (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:@"MSA" withExtension:@"momd"]; 
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; 
    return _managedObjectModel; 
} 


/** 
* Return the NSPersistenceStoreCoordinator used in CoreData if it does'nt exist 
* with the options: dictionaryWithObjectsAndKeys and NSMigratePersistentStoresAutomaticallyOption set to YES 
* 
* @return PersistanceStoreCoordinator used by CoreData 
*/ 
- (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:@"MSA.sqlite"]; 
    NSError *error = nil; 
    NSString *failureReason = @"There was an error creating or loading the application's saved data."; 

    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: 
          [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, 
          [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; 


    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options 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; 
} 

/** 
* Creates NSManagedObjectContext for CoreData 
* 
* @return NSManagedObjectContext for CoreData 
*/ 

- (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] initWithConcurrencyType:NSMainQueueConcurrencyType]; 
    [_managedObjectContext setPersistentStoreCoordinator:coordinator]; 
    return _managedObjectContext; 
} 

/** 
* Creates NSManagedObjectContext for CoreData 
* 
* @return NSManagedObjectContext for CoreData 
*/ 

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

    _childManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; 
    NSManagedObjectContext * cont = [self managedObjectContext]; 

    [_childManagedObjectContext setParentContext:cont]; 

    return _childManagedObjectContext; 
} 

Программа сбои в линии:

Target * target = [[Target alloc] initWithEntity:ent insertIntoManagedObjectContext:context]; 

следующих ошибка:

2015-08-13 15:52:51.720 MSA[3262:71338] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Target managedObjectModel]: unrecognized selector sent to instance 0x7ffa28e506a0' 
*** First throw call stack: 
(
    0 CoreFoundation      0x000000010c751c65 __exceptionPreprocess + 165 
    1 libobjc.A.dylib      0x000000010c02ebb7 objc_exception_throw + 45 
    2 CoreFoundation      0x000000010c7590ad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205 
    3 CoreFoundation      0x000000010c6af13c ___forwarding___ + 988 
    4 CoreFoundation      0x000000010c6aecd8 _CF_forwarding_prep_0 + 120 
    5 CoreData       0x000000010c27fea3 -[NSManagedObject initWithEntity:insertIntoManagedObjectContext:] + 83 
    6 MSA         0x00000001090db227 +[Target initWithCoreData] + 183 
    7 MSA         0x00000001090db32a +[Target setTarget:new:targetISO:lastUpdate:] + 154 
    8 MSA         0x00000001090c53bb -[MSASetTargetView applyTargetButton:] + 651 
    9 UIKit        0x0000000109bfbd62 -[UIApplication sendAction:to:from:forEvent:] + 75 
    10 UIKit        0x0000000109d0d50a -[UIControl _sendActionsForEvents:withEvent:] + 467 
    11 UIKit        0x0000000109d0c499 -[UIControl touchesBegan:withEvent:] + 224 
    12 UIKit        0x0000000109c487be -[UIWindow _sendTouchesForEvent:] + 325 
    13 UIKit        0x0000000109c49282 -[UIWindow sendEvent:] + 682 
    14 UIKit        0x0000000109c0f541 -[UIApplication sendEvent:] + 246 
    15 UIKit        0x0000000109c1ccdc _UIApplicationHandleEventFromQueueEvent + 18265 
    16 UIKit        0x0000000109bf759c _UIApplicationHandleEventQueue + 2066 
    17 CoreFoundation      0x000000010c685431 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 
    18 CoreFoundation      0x000000010c67b2fd __CFRunLoopDoSources0 + 269 
    19 CoreFoundation      0x000000010c67a934 __CFRunLoopRun + 868 
    20 CoreFoundation      0x000000010c67a366 CFRunLoopRunSpecific + 470 
    21 GraphicsServices     0x000000010f581a3e GSEventRunModal + 161 
    22 UIKit        0x0000000109bfa8c0 UIApplicationMain + 1282 
    23 MSA         0x00000001090e798f main + 111 
    24 libdyld.dylib      0x000000010d6da145 start + 1 
    25 ???         0x0000000000000001 0x0 + 1 
) 
libc++abi.dylib: terminating with uncaught exception of type NSException 

Я понятия не имею, что я делаю неправильно ... Все, что я нахожу в сети, связано с созданием контекста в нем.

Большое спасибо!

ответ

0

Я нашел ответ! Я создаю Target неправильно, это должно быть:

+ (Target*)initWithCoreData{ 

NSManagedObjectContext * context = [[CoreDataWrapper sharedInstance] childManagedObjectContext]; 

Target * target = [NSEntityDescription insertNewObjectForEntityForName:@"Target" 
               inManagedObjectContext:context]; 


return target; 
} 
Смежные вопросы