【发布时间】:2013-09-11 22:23:05
【问题描述】:
我有一个 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;
}
【问题讨论】:
-
崩溃发生在代码的什么地方?
-
能否粘贴控制台抛出的异常?另外,TrainingCurse 是 NSManagedEntity 吗?
-
不要在方法前加上
get。 -
@bbum,我很好奇 - 为什么 Objective-c 方法不应该以
get为前缀? -
因为
get保留给通过参数通过引用返回的方法。在这种情况下,它应该只是trainingCourseWithId:。
标签: ios objective-c