当我向关系集添加新的托管对象时,为什么我的应用程序崩溃了?

时间:2010-05-24 19:00:26

标签: iphone core-data

我有这个简单的核心数据模型:

问题,答案

每个问题都有4个答案。

代码如下: Question.m

@interface Question :  NSManagedObject  
{
}

@property (nonatomic, retain) NSString * questionText;
@property (nonatomic, retain) NSSet* answers;
@property (nonatomic, retain) Package * package;

@end


@interface Question (CoreDataGeneratedAccessors)
- (void)addAnswersObject:(NSManagedObject *)value;
- (void)removeAnswersObject:(NSManagedObject *)value;
- (void)addAnswers:(NSSet *)value;
- (void)removeAnswers:(NSSet *)value;

@end

Answer.m

@class Question;

@interface Answer :  NSManagedObject  
{
}

@property (nonatomic, retain) NSString * answerText;
@property (nonatomic, retain) NSNumber * correct;
@property (nonatomic, retain) Question * question;

@end

问题是当我尝试使用addAnswersObject添加问题的答案时。

这是导致应用程序崩溃的代码部分:

for (CXMLElement *theElement in theNodes)
    {   
        Question *qst = [NSEntityDescription insertNewObjectForEntityForName:@"Question" inManagedObjectContext:moc];

        // Create a counter variable as type "int"
        int counter;

        // Loop through the children of the current  node
        for(counter = 0; counter < [theElement childCount]; counter++) {



            if([[[theElement childAtIndex:counter] name] isEqualToString: @"question"])
                [qst setQuestionText:[[theElement childAtIndex:counter] stringValue]];
            if([[[theElement childAtIndex:counter] name] isEqualToString: @"answer"]) {
                Answer *answer = [NSEntityDescription insertNewObjectForEntityForName:@"Answer" inManagedObjectContext:moc];

                [answer setAnswerText:[[theElement childAtIndex:counter] stringValue]];

                CXMLElement *answerElement = (CXMLElement *)[theElement childAtIndex:counter];

                if([[[answerElement attributeForName:@"correct"] stringValue] isEqualToString:@"YES"]) {
                    [answer setCorrect:[NSNumber numberWithBool:YES]];
                } else { 
                    [answer setCorrect:[NSNumber numberWithBool:NO]];
                }

                [qst addAnswersObject:answer]; //The app crash here

            }

        }

这是来自控制台的日志:

  

2010-05-24 20:02:38.475 Fgq [5670:40b]   *** - [NSUserDefaults objectForKey:]:发送到解除分配的实例的消息   0x3c179a0程序接收信号:   “EXC_BAD_ACCESS”。

我多次从对象数据模型中重新导出所有对象而没有成功,我检查了所有关系,似乎一切正常。

可能是什么问题?

2 个答案:

答案 0 :(得分:0)

如果您在NSLog(@"qst: %@:, qst);实例的qst电话后立即添加-insertNewObjectForEntityName:inManagedObjectContext:,控制台会报告什么?

如果您在NSLog(@"answer: %@:, answer);实例的answer电话后立即添加-insertNewObjectForEntityName:inManagedObjectContext:,控制台会报告什么?

答案 1 :(得分:0)

这里报告的是NSLog(@“qst:%@”,qst);

  

2010-05-24 23:37:33.948   FGQ [452:207] qst:    (实体:   题; id:0x3c19ab0      ;数据:{       答案=(       );       package = nil;       questionText = nil; })