NSFetchRequest 返回值
Posted
技术标签:
【中文标题】NSFetchRequest 返回值【英文标题】:NSFetchRequest return value 【发布时间】:2012-03-01 11:59:31 【问题描述】:我不明白为什么这段代码会返回错误
- (void) deleteCategoriesWithNoProducts
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Category" inManagedObjectContext:self.itemDatabase.managedObjectContext];
[request setEntity:entity];
//NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Category"];
NSSortDescriptor *sortDescriptor = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
NSError *error;
NSArray *fetchResults = [self.itemDatabase.managedObjectContext executeFetchRequest:request error:&error];
这是错误:
-[__NSArrayI key]: unrecognized selector sent to instance 0x8267ad0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI key]: unrecognized selector sent to instance 0x8267ad0'
希望有人可以帮助我。谢谢!
【问题讨论】:
【参考方案1】:这是你的错误:
NSSortDescriptor *sortDescriptor = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]];
应该是:
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
那行也应该在编译器中给你一个警告。
【讨论】:
别忘了在方法结束时释放资源。 哦,原来如此,有点棘手啊。感谢@yuji 指出这一点。以上是关于NSFetchRequest 返回值的主要内容,如果未能解决你的问题,请参考以下文章
NSFetchRequest 在第一次运行时返回对象,但以后不返回