NSPredicate用于检测的属性的类(NSPredicate for detecting Cla

2019-10-18 18:20发布

我有事件,每个事件都有与NSManagedObject娱乐一对一的关系,娱乐有一对多的关系,并有事件的NSSet

@interface Event : NSManagedObject
@property (nonatomic, retain) NSDate *creationDate;
@property (nonatomic, retain) NSDate * date;
@property (nonatomic, retain) NSString * objectId;
@property (nonatomic, retain) NSString * price;
@property (nonatomic, retain) Entertainment *entertainment;
@property (nonatomic, retain) Place *place;
@property (nonatomic, retain) NSString *townName;
- (void)fillProperties:(NSDictionary *)JSON;
@end

@interface Entertainment : NSManagedObject
@property (nonatomic, retain) NSString * additionalInfo;
@property (nonatomic, retain) NSNumber * allCommentsLoaded;
@property (nonatomic, retain) id image;
@property (nonatomic, retain) NSString * imageURL;
@property (nonatomic, retain) NSString * info;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * objectId;
@property (nonatomic, retain) NSSet *comments;
@property (nonatomic, retain) NSSet *events;
- (void)fillProperties:(NSDictionary *)JSON;
@end

娱乐有很多子类所以我需要为获取事件,具有特定类的娱乐创造这样NSFetchedResultController

我试着使用

- (NSFetchedResultsController *)fetchedResultsControllerForEventsFromEntertainment:(Class)className 
{
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([Event class])];
    fetchRequest.predicate = [NSPredicate predicateWithFormat:@"entertainment isMemberOfClass: %@", [className class]];
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"objectId" ascending:YES];
    fetchRequest.sortDescriptors = @[sortDescriptor];
    fetchRequest.fetchBatchSize = 20;
    NSFetchedResultsController *fetchResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
    return fetchResultsController;
}

但我得到的错误:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
 reason: 'Unknown/unsupported comparison predicate operator type'
***

我看,那个时候我们使用SQLite的工作,这种方法isMemberOfClass不行的,因为SQLite的不知道这样的方法。 在通常的NSPredicate例如简单的数组它必须工作。

那么,如何可以获取来自SQLite的事件,具有特定类的娱乐?

Answer 1:

这是不可能指实体名称或类名在(基于SQLite的)核心数据获取请求的谓词。

但获取任何子实体的读取请求时,而不是对象指定的实体的唯一对象,只需设置

[fetchRequest setIncludesSubentities:NO];


文章来源: NSPredicate for detecting Class of the property