0

I have an iOS application that selects ARC option when the application is firstly created.

I have a question about some coding way that causes some crash. I do not know why the code crash happens if I declare and set memory allocation for a variable in one code line, and then assigning real value for that variable in another line.

Thank you for your help.

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

The full method:

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

}
Thomas.Benz
  • 8,381
  • 9
  • 38
  • 65

2 Answers2

1

1) check if results even has an entry:

assert(results.count);

OR

if(results.count) ... 

2) if TrainingCourse is a MOM, you have to init it via initWithEntity

Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
  • thank you very much. results.count really returns 1 entry. The problem was I used "init" method instead of working "initWithEntity" method. – Thomas.Benz Sep 12 '13 at 20:04
1

Because TrainingCourse inherits from NSManagedObject, you can't initialize a TrainingCourse variable like you do with a full-fledged Objective-C object using alloc/init. To allocate a new managed object, use NSEntityDescription's class method +insertNewObjectForEntityForName:inManagedObjectContext: instead.

TrainingCourse *course = [NSEntityDescription insertNewObjectForEntityForName:[[TrainingCourse class] name] inManagedObjectContext:self.managedObjectContext];
Andrew
  • 7,630
  • 3
  • 42
  • 51