【问题标题】:Code crash with alloc, init [duplicate]alloc,init的代码崩溃[重复]
【发布时间】: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


【解决方案1】:

1) 检查 results 是否有条目:

assert(results.count);

if(results.count) ... 

2) 如果 TrainingCourse 是 MOM,则必须通过 initWithEntity 初始化它

【讨论】:

  • 非常感谢。 results.count 确实返回 1 个条目。问题是我使用“init”方法而不是“initWithEntity”方法。
【解决方案2】:

因为TrainingCourse 继承自NSManagedObject,所以您不能像使用alloc/init 对成熟的Objective-C 对象那样初始化TrainingCourse 变量。要分配新的托管对象,请改用 NSEntityDescription 的类方法+insertNewObjectForEntityForName:inManagedObjectContext:

TrainingCourse *course = [NSEntityDescription insertNewObjectForEntityForName:[[TrainingCourse class] name] inManagedObjectContext:self.managedObjectContext];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    相关资源
    最近更新 更多