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