2013-02-03 3 views
36

CoreData에 약간의 문제가 있습니다. 새 Object를 삽입하고 싶습니다. 그래서 먼저 Object를 생성해야합니다.CoreData : 오류 : NSManagedObject 클래스에서 지정된 초기화 프로그램을 호출하지 못했습니다.

Challenges *newChallenge = [[Challenges alloc] init]; 
[newChallenge setName:@"TestChallenge"]; 
[newChallenge setRounds:[[NSNumber alloc] initWithInt:12]]; 
[newChallenge setShots:[[NSNumber alloc] initWithInt:5]]; 
[newChallenge setDate:[NSDate date]]; 

그러나 그러나 ALLOC 초기화 후 나는이 오류를 얻을 : 해킹 잘못

CoreData: error: Failed to call designated initializer on NSManagedObject class 'Challenges' 

을 무슨 일을이 해당 코드에 의해 이루어집니다?

답변

58

나는 문제가 과제가 NSManagedObject 클래스라고 생각하고는 지정된 초기화가 필요합니다

initWithEntity:insertIntoManagedObjectContext: 

대신

Read More..

+1

을 당신이 * 지정 * 초기화를 의미 생각 여기에 당신이 상용구 줄이려고하고 코드를 읽기 쉽게 만들 수있는 방법이다. – jlehr

+1

@jiehr : 물론 나는 이니셜 라이저 지정을 의미했습니다 - 많은 감사합니다! (나는 대답을 편집했다) – duDE

13

NSManagedObject

Challenges *newChallenge = [[Challenges alloc] init]; 
그냥 alloc/ init 수 없습니다 너 평소처럼로 할거야.. 사실 지정된 초기화는 다음과 같습니다 이제 initWithEntity:insertIntoManagedObjectContext:

, 실제 오류에 대한 애플 states in the documentation는 것을 : 그래서

Important: This method is the designated initializer for NSManagedObject. You must not initialize a managed object simply by sending it init.

, 당신은 당신이 그것을 초기화하기 위해 2 가지가 필요하다고 볼 수 있었다, NSEntityDescription (인스턴스화하려는 엔터티) 및 NSManagedObjectContext (새 개체를 만들 컨텍스트)입니다. 각각의 새로운 객체가 출생에서 이러한 속성을 정의합니다

-(void) awakeFromInsert { 
    self.date = [NSDate date]; 
    self.rounds = @(12); 
    self.shots = @(5); 
} 

: 당신의 도전 클래스는 NSManagedObject과 날짜 인 경우

4

Additionaly, 라운드과 촬영 당신이 방법을 추가 할 수 있습니다 그 속성으로 정의됩니다.

30

"괜찮습니까? 그렇다면 어떻게해야합니까?" (나처럼) 그렇게처럼 entityForName 방법을 사용하여이 작업을 수행 :이 도움이

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Challenges" inManagedObjectContext:self.managedObjectContext]; 

Challenges *newChallenge = [[Challenge alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext]; 

희망,이 스레드는 나에게 많은 도움이되었습니다!

+0

그것은 나를 위해 일한다. 그러나 왜? – Allan

4

다른 사람들은 이미 왜 작동하지 않는지 설명했습니다.

@implementation NSManagedObject(MyPrivateAdditions) 

+ (id)insertNewObjectInContext:(NSManagedObjectContext *)context 
{ 
    return [NSEntityDescription insertNewObjectForEntityForName:self.className inManagedObjectContext:context]; 
} 

@end 

지금 당신이 할 수 있습니다 :

Challenges *newChallenge = [Challenge insertNewObjectInContext:context]; 
+0

허용 된 답변이어야합니다. –

관련 문제