NSError **问题在多函数调用中传回传播

时间:2017-08-05 06:43:03

标签: ios objective-c error-handling nserror

面对多功能调用中错误反向传播的问题。

例如,

NSError *error = nil;
EMSPlanFolder *planner = [[EMSPlanFolder sharedPlanBuilder] buildPlanFromParsePlan:plan withError:&error];
if (error) {
   //error
}

接下来,它将起作用:

- (EMSPlanFolder*)buildPlanFromParsePlan:(EMParsedPlan*)parsedPlan withError:(NSError *__autoreleasing*)err
{
 ....
 ....
 [self deserializePlan:parsedPlan forPlan:newPlanFolder allowingNoEndDate:NO withError:err];
  if(err && *err) {
   [newPlanFolder.managedObjectContext performBlockAndWait:^{
 [EMSPlanFolder deletePlan:newPlanFolder];
    }];
  return nil;
  }
 return newPlanFolder;
}

接下来,进入:

   - (void)deserializePlan:(NSArray*)planElements forPlan:(LMSPlanFolder*)planFolder allowingNoEndDate:(BOOL)allowNoEndDate withError:(NSError *__autoreleasing*)err {
     ....
     ....
     if(err) {
      *err = [NSError errorWithDomain:@"Application" code:-1 userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Plan was not found."]}];
     }
     return;
    }

问题是,当它反向传播到第一个代码片段时会导致崩溃。有关它的任何建议

1 个答案:

答案 0 :(得分:0)

Apple框架通常在嵌套的自动释放池中执行块。您的错误引用是自动释放,因此在块执行完毕后会释放错误。为避免这种情况,请使用强大的本地__block变量来保留错误。尝试类似的东西:

__block NSError *theError = nil;

[context performBlockAndWait:^{
     //
    [self deserializePlan:parsedPlan 
                  forPlan:newPlanFolder 
        allowingNoEndDate:NO 
                withError:&theError]; // <- store the error ARP safe
}];
*err = theError;