我一直关注this教程到T,但是当我运行我的应用时,每次启动都会失败并出现以下错误:
* 由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'+ entityForName:nil不是 合法的NSManagedObjectContext参数搜索实体名称 'ArticleInfo''
但是我无法弄清楚我做错了会导致什么。作为我所做的事情的背景,我有一个带有一个名为ArticleInfo的实体的datamodel文件,其中有一堆不同类型的属性(如果需要注意的话,有一些瞬态)。根据{{3}}文章的建议,我将NSManagedObject
归为ArticleInfo
。
如果值得注意,我在数据模型中创建了preview
,wordsInBody
和progress
瞬态(我给了position
默认值0
在数据模型检查器中)。所以在子类中,我按如下方式制作了自定义getter:
- (NSString *)preview {
[self willAccessValueForKey:@"preview"];
NSString *preview = [self primitiveValueForKey:@"preview"];
[self didAccessValueForKey:@"preview"];
if (self.body.length < 200) {
preview = self.body;
}
else {
preview = [self.body substringWithRange:NSMakeRange(0, 200)];
}
return preview;
}
- (NSNumber *)progress {
[self willAccessValueForKey:@"progress"];
NSNumber *progress = [self primitiveValueForKey:@"progress"];
[self didAccessValueForKey:@"progress"];
if (self.body.length == 0) {
progress = @100;
}
else {
progress = @(100 * [self.position intValue] / [self.wordsInBody intValue]);
}
return progress;
}
- (NSNumber *)wordsInBody {
[self willAccessValueForKey:@"wordsInBody"];
NSNumber *wordsInBody = [self primitiveValueForKey:@"wordsInBody"];
[self didAccessValueForKey:@"wordsInBody"];
if (!wordsInBody) {
__block int numberOfWordsInBody = 0;
NSRange range = {0, self.body.length};
[self.body enumerateSubstringsInRange:range options:NSStringEnumerationByWords usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
numberOfWordsInBody++;
}];
wordsInBody = @(numberOfWordsInBody);
}
return wordsInBody;
}
(同样,不确定这是否相关。)
现在在我的主viewcontroller类(具有tableview的那个我正在使用NSFetchedResultsController
)我声明了属性,并覆盖了它的getter:
在.h:
@property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController;
在.m:
- (NSFetchedResultsController *)fetchedResultsController {
if (!_fetchedResultsController) {
NSManagedObjectContext *context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"ArticleInfo" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = entity;
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
request.sortDescriptors = [NSArray arrayWithObject:descriptor];
request.fetchBatchSize = 20;
NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:nil cacheName:@"Root"];
_fetchedResultsController = fetchedResultsController;
_fetchedResultsController.delegate = self;
}
return _fetchedResultsController;
}
但是,再次,它一直给我在应用程序启动时的错误。我究竟做错了什么导致了这个错误?
答案 0 :(得分:2)
NSEntityDescription * entity = [NSEntityDescription entityForName:@“ArticleInfo”inManagedObjectContext:context]
这里的东西是零。记录上下文和实体以查看哪一个。也许你的模型中的实体名称不是“ArticleInfo”(错字?)或者你的app委托在创建上下文时遇到问题。