0

アプリケーションが最初に作成されたときに ARC オプションを選択する iOS アプリケーションがあります。

クラッシュの原因となるコーディング方法について質問があります。あるコード行で変数のメモリ割り当てを宣言して設定し、別の行でその変数に実際の値を割り当てると、コード クラッシュが発生する理由がわかりません。

ご協力ありがとうございました。

// 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;

}
4

2 に答える 2

1

1) 結果にエントリがあるかどうかを確認します。

assert(results.count);

また

if(results.count) ... 

2) TrainingCourse が MOM の場合は、次の方法で初期化する必要があります。initWithEntity

于 2013-09-11T22:41:49.020 に答える