2012-07-27 2 views
0

Obj-C 및 CoreData가 처음입니다. 과거에 CoreData를 성공적으로 사용했지만 내 managedObject 중 하나의 속성에 값을 할당하려고하면 문제가 발생합니다.핵심 데이터를 사용하고 값을 변경할 때 EXC_BAD_ACCESS

그래서, 나는 내가 managedObjectContext를 인스턴스화하고 저장할 managedObject를 만들었습니다.

if (managedObjectContext == nil) 
    { 
     managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
    } 

Lesson *Lesson1 = [NSEntityDescription insertNewObjectForEntityForName:@"Lesson" inManagedObjectContext:managedObjectContext]; 

내가 다음 managedObject의 값을 편집하고 그것을 저장하기 위해 이동 : 나는 응용 프로그램을 실행하는 경우

Lesson1.productID = 1; 
    Lesson1.purchaseStatus = 1; 
    Lesson1.title = @"Happy Birthday to You"; 
    Lesson1.subtitle = @"Patty & Mildred Hill"; 
    Lesson1.titleAndSubtitle = @"Happy Birthday to You - Patty & Mildred Hill"; 
    Lesson1.coverArtFilename = @"beethoven.png"; 
    Lesson1.durationLabel = @"0:11"; 
    Lesson1.notes = @"123"; 
    Lesson1.timing = @"3/4"; 
    Lesson1.keySignature = @"G"; 
    Lesson1.difficultyImageFilename = @"easy.png"; 
    Lesson1.lessonDescription = @"Originally, this song piece was called 'Good Morning to All' and was sung to and by children in school."; 
    Lesson1.sheetFilename = @"1_score"; 
    Lesson1.midiFilename = @"happyBirthdayToYou"; 
    Lesson1.materialsFilename = @"1_score"; 
    Lesson1.roll = @"happyBirthdayToYou"; 
    Lesson1.duration = 11; 
    Lesson1.startingIndicatorPosition = 175; 
    Lesson1.rollPositionArray = [NSArray arrayWithObjects: /* 0 */ [NSNumber numberWithInteger:0], 
                  /* 1 */ [NSNumber numberWithInteger:0],  
                  /* 2 */ [NSNumber numberWithInteger:0], 
                  /* 3 */ [NSNumber numberWithInteger:-65], 
                  /* 4 */ [NSNumber numberWithInteger:-100], 
                  /* 5 */ [NSNumber numberWithInteger:-135], 
                  /* 6 */ [NSNumber numberWithInteger:-185], 
                  /* 7 */ [NSNumber numberWithInteger:-185], 
                  /* 8 */ [NSNumber numberWithInteger:-241], 
                  /* 9 */ [NSNumber numberWithInteger:-306], 
                  /* 10 */ [NSNumber numberWithInteger:-341], 
                  /* 11 */ [NSNumber numberWithInteger:-376], 
                  /* 12 */ [NSNumber numberWithInteger:-426], 
                  /* 13 */ [NSNumber numberWithInteger:-426], 
                  /* 14 */ [NSNumber numberWithInteger:-483], 
                  /* 15 */ [NSNumber numberWithInteger:-548], 
                  /* 16 */ [NSNumber numberWithInteger:-582], 
                  /* 17 */ [NSNumber numberWithInteger:-617], 
                  /* 18 */ [NSNumber numberWithInteger:-666], 
                  /* 19 */ [NSNumber numberWithInteger:-701], 
                  /* 20 */ [NSNumber numberWithInteger:-737], 
                  /* 21 */ [NSNumber numberWithInteger:-799], 
                  /* 22 */ [NSNumber numberWithInteger:-834], 
                  /* 23 */ [NSNumber numberWithInteger:-868], 
                  /* 24 */ [NSNumber numberWithInteger:-918], 
                  nil]; 

    NSError *error; 
    if (![managedObjectContext save:&error]) { 
     NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]); 
    } 

을이 시점에서, 그것은 나에게 오류를 제공합니다 : EXC_BAD_ACCESS (코드 = 2, 주소 = 0x1) productID 값을 변경하려고 할 때. 또한 그것은 "int *"from "int"에 할당 된 포인터 변환에 호환되지 않는 정수임을 알리는 경고 메시지를 표시합니다.

일부 디버깅을 수행하고 내 개체가 nil이고 아니다 나는 출력 내 managedObjectContext의 설명은 내가 얻을 때 :.

Printing description of self->managedObjectContext: 
<NSManagedObjectContext: 0x7e8d8b0> 

그리고 내 개체를 인쇄, 내가 얻을 :

내 디버깅 기술이 작은 지식으로 인해 제한됩니다
Printing description of Lesson1: 
<NSManagedObject: 0x7e927e0> (entity: Lesson; id: 0x7e7fce0 <x-coredata:///Lesson/tA7BFE664-F978-4983-B5DC-14D3F3ED49812> ; data: { 
    coverArtFilename = nil; 
    difficultyImageFilename = nil; 
    duration = 0; 
    durationLabel = nil; 
    keySignature = nil; 
    lessonDescription = nil; 
    materialsFilename = nil; 
    midiFilename = nil; 
    productID = nil; 
    purchaseStatus = 0; 
    roll = nil; 
    rollPositionArray = nil; 
    sheetFilename = nil; 
    startingIndicatorPosition = 0; 
    subtitle = nil; 
    timing = nil; 
    title = nil; 
    titleAndSubtitle = nil; 
}) 

내가 그렇게해야 누군가가 올바른 방향으로 나를 가리킬 수 있다면 나는 ver 일 것이다. 고마워. 고맙습니다.

편집은

내 NSManagedObjectContext는 기본 방법으로 정의 하였다.

#import "AppDelegate.h" 

@implementation AppDelegate 

@synthesize window = _window; 
@synthesize managedObjectContext = __managedObjectContext; 
@synthesize managedObjectModel = __managedObjectModel; 
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator; 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    return YES; 
} 

- (void)applicationWillResignActive:(UIApplication *)application 
{ 
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 
} 

- (void)applicationDidEnterBackground:(UIApplication *)application 
{ 
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 
} 

- (void)applicationWillEnterForeground:(UIApplication *)application 
{ 
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 
} 

- (void)applicationDidBecomeActive:(UIApplication *)application 
{ 
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 
} 

- (void)applicationWillTerminate:(UIApplication *)application 
{ 
    // Saves changes in the application's managed object context before the application terminates. 
    [self saveContext]; 
} 

- (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:@"iLessons_Piano" 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:@"iLessons_Piano.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]); 
     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 

답변

4

제품 ID 또는 다른 숫자 속성 NSNumber* 아닌가 : 나는 아래에있는 내 AppDelegate.m이 첨부했습니다? 당신이 purchaseStatus, durationstartingIndicatorPosition

+0

에 대한

Lesson1.productID = [NSNumber numberWithInt:1]; 

같은 시도 할 수 나는 그 전에 시도하지만 :( – Barks

+1

그래서 이러한 속성은 그것이 "의 NSNumber *"와 "INT *"사이에 호환되지 않는 변환이라고 말했다 NSManagedObject 클래스를 어떻게 생성 했습니까?이 속성들을 정수로 정의했다면 NSManagedObject 클래스를 어떻게 생성 했습니까? – mask8

+0

NSManagedObjectContext 생성 방법을 보여주기 위해 AppDelegate.m을 게시했습니다. 내 모델 "Integer 32"로 productID 특성을 정의했습니다. – Barks

관련 문제