抱歉,这有点含糊,但这只是问题的一半。
我有一个正在使用的基于文档的核心数据应用程序,它正在执行运行时所告知的内容,并且不会产生任何错误。但是,当用户保存文档时,文档弹出“文档xyz”无法保存为“ xyz”。发生多个验证错误”警报。
我的问题是-您从哪里开始寻求解决/调试此问题?由于程序没有在调试器中崩溃,因此我没有堆栈跟踪等信息。这是否可能是错误的实体关系,还是没有数据保存在实体的非可选属性中?...是否有办法准确说明什么是验证失败?
最好的方式进行的任何建议,不胜感激。
与此相关的是,什么/如何才能在将来捕获这种错误,从而使它不至于影响用户,这是最好的方法。
非常感谢
验证错误表明问题出在保存文档时应用的验证谓词上。反过来,这意味着您尝试保存的某些数据类型错误或值错误。
如果您从保存操作捕获错误返回,则 userInfo 字典应包含有关失败的详细信息。
好的,正如TechZen建议的那样,从保存操作中捕获错误。将以下内容添加到MyDocument.m
- (NSError *)willPresentError:(NSError *)error {
// Only deal with Core Data Errors
if (!([[error domain] isEqualToString:NSCocoaErrorDomain])) {
return error;
}
NSInteger errorCode = [error code];
if ((errorCode < NSValidationErrorMinimum) || (errorCode > NSValidationErrorMaximum)) {
return error;
}
// If there is only 1 error, let the usual alert display it
if (errorCode != NSValidationMultipleErrorsError) {
return error;
}
// Get the errors. NSValidationMultipleErrorsError - the errors are in an array in the userInfo dictionary for key NSDetailedErrorsKey
NSArray *detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey];
NSUInteger errorCount = [detailedErrors count];
NSMutableString *errorString = [NSMutableString stringWithFormat:@"There are %lu validation errors:-", errorCount];
for (int i = 0; i < errorCount; i++) {
[errorString appendFormat:@"%@\n",
[[detailedErrors objectAtIndex:i] localizedDescription]];
}
// Create a new error with the new userInfo and return it
NSMutableDictionary *newUserInfo = [NSMutableDictionary dictionaryWithDictionary:[error userInfo]];
[newUserInfo setObject:errorString forKey:NSLocalizedDescriptionKey];
NSError *newError = [NSError errorWithDomain:[error domain] code:[error code] userInfo:newUserInfo];
return newError;
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果有100个错误,那么您将收到一个包含100个项目的警报,这并不是最好的警报,但这是处理保存错误的一个很好的起点。