Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/95.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 使用alloc、init的代码崩溃_Ios_Objective C - Fatal编程技术网

Ios 使用alloc、init的代码崩溃

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

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

}
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];