0

我有一个 iOS 应用程序,它在首次创建应用程序时选择了 ARC 选项。

我对某些导致崩溃的编码方式有疑问。如果我在一个代码行中为变量声明并设置内存分配,然后在另一行中为该变量分配实际值,我不知道为什么会发生代码崩溃。

谢谢您的帮助。

// if I use one line of code as follows, then I do NOT have code crash
TrainingCourse* course = [results objectAtIndex:0]; 


// BUT, if I separate the code line above into the 2 line of codes as follows, I get code crash
TrainingCourse* course = [[TrainingCourse alloc] init];
course = [results objectAtIndex:0]; // crash appears here

完整的方法:

-(TrainingCourse*) getTrainingCourseWithId:(NSNumber*)trainingCourseId
{

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"TrainingCourse" inManagedObjectContext:self.managedObjectContext]];


    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"trainingCourseId == %@", trainingCourseId];
    [request setPredicate:predicate];

    NSError *error = nil;
    NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error];

    // if I use one line of code as follows, then I do NOT see any code crash
    TrainingCourse* course = [results objectAtIndex:0]; 


    // BUT, if I separate the code line above into the 2 line of codes as follows, I get code crash
    // TrainingCourse* course = [[TrainingCourse alloc] init];
    // course = [results objectAtIndex:0]; // crash appears here

    return course;

}
4

2 回答 2

1

因为TrainingCourse继承自NSManagedObject,所以不能TrainingCourse像使用 alloc/init 对成熟的 Objective-C 对象那样初始化变量。要分配新的托管对象,请改用 NSEntityDescription 的类方法+insertNewObjectForEntityForName:inManagedObjectContext :。

TrainingCourse *course = [NSEntityDescription insertNewObjectForEntityForName:[[TrainingCourse class] name] inManagedObjectContext:self.managedObjectContext];
于 2013-09-11T22:56:42.093 回答
1

1)检查结果是否甚至有一个条目:

assert(results.count);

或者

if(results.count) ... 

2)如果 TrainingCourse 是一个 MOM,你必须通过它来初始化它initWithEntity

于 2013-09-11T22:41:49.020 回答