代码崩溃与alloc,init

时间:2013-09-11 22:23:05

标签: ios objective-c

我有一个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;

}

2 个答案:

答案 0 :(得分:1)

1)检查结果是否有条目:

assert(results.count);

OR

if(results.count) ... 

2)如果TrainingCourse是MOM,则必须通过initWithEntity

初始化

答案 1 :(得分:1)

由于TrainingCourse继承自NSManagedObject,因此无法像使用alloc / init对完整的Objective-C对象一样初始化TrainingCourse变量。要分配新的托管对象,请改用NSEntityDescription的类方法+insertNewObjectForEntityForName:inManagedObjectContext:

TrainingCourse *course = [NSEntityDescription insertNewObjectForEntityForName:[[TrainingCourse class] name] inManagedObjectContext:self.managedObjectContext];