【问题标题】:NSPredicate to-many relationship with inheritanceNSPredicate 与继承的多对多关系
【发布时间】:2013-01-27 19:45:30
【问题描述】:

我正在开发一个有 Post 对象的应用程序,每个 Post 可以有许多实体(提及、主题标签和链接),每个实体都有一个 Post。我有一个实体的主类,然后我有三个子类。

Mention : Entity

我的提及类具有以下属性:

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * userId; 

我现在想创建一个 NSPredicate 来查找所有提及某个用户和 userId 的帖子,但我不知道该怎么做。

我已经尝试过这样的一些事情:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY mentions.userId like %@",  [Session currentUser].userId];
// That doesn't work since Post(s) have many entities and not Mention(s).
// I have also tried something like this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY entities.mentions.userId like %@",  [Session currentUser].userId];
// And that didn't work either. 

关于如何最好地找到所有提及具有特定 userId 的特定用户的帖子有什么想法吗?

【问题讨论】:

    标签: ios cocoa-touch core-data nspredicate


    【解决方案1】:

    存在继承,因此您不必对相同的属性进行两次编码。否则,具有父对象的托管对象就像其他托管对象一样。

    因此,你应该给你的帖子三个关系:

    Post
     hashes   Hash        
     mentions Mention     
     links    Link        
    

    那么你的问题就变得微不足道了:

    [NSPredicate predicateWithFormat:@"ANY hashes.userID = %@", _currentUser.userID];
    

    like 没有意义,因为userID 可能是唯一的,而LIKE 比简单的等价要昂贵得多。


    如果您只想与一类实体建立一对多关系,则必须在 Entity 中包含另一个属性,例如NSNumber,表示它是什么类型。假设您使用 enum 使数字类型更具可读性,谓词将如下所示:

    [NSPredicate predicateWithFormat:
           @"ANY (entity.type == %@ && entity.userID == %@)",
           @(EntityTypeMention), _currentUser.userID];       
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多