Ios 使用alloc、init的代码崩溃
我有一个iOS应用程序,在第一次创建应用程序时选择ARC选项 我有一个关于导致崩溃的编码方式的问题。如果我在一行代码中声明并设置变量的内存分配,然后在另一行中为该变量赋值,我不知道为什么会发生代码崩溃 谢谢你的帮助Ios 使用alloc、init的代码崩溃,ios,objective-c,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 sep
// 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;
}
1) 检查结果是否有条目:
assert(results.count);
或
2) 如果TrainingCourse是MOM,您必须通过
initWithEntity
初始化它,因为TrainingCourse
继承自NSManagedObject
,您不能像使用alloc/init初始化成熟的Objective-C对象那样初始化TrainingCourse
变量。要分配新的托管对象,请改用NSEntityDescription的类方法
崩溃发生在代码中的什么地方?你能粘贴控制台抛出的异常吗?另外,TrainingCurse是NSManageIdentity吗?不要用
get
作为方法的前缀@bbum,我很好奇-为什么不应该用get
作为objective-c方法的前缀?因为get
对于通过参数引用返回的方法是保留的。在这种情况下,它应该是trainingCourseWithId:
。非常感谢。results.count实际上返回1个条目。问题是我使用了“init”方法,而不是使用“initWithEntity”方法。
if(results.count) ...
TrainingCourse *course = [NSEntityDescription insertNewObjectForEntityForName:[[TrainingCourse class] name] inManagedObjectContext:self.managedObjectContext];