【问题标题】:Validating data and looping through NSSet验证数据并通过 NSSet 循环
【发布时间】:2014-02-24 08:37:40
【问题描述】:

我在 xcode 中有一个 CoreData (SQLite) 数据模型,如下所示:

Friends Table
  email
  name
  username
  belongsToGroups

Groups Table
  title
  peopleInGroup

所以belongsToGroups和peopleInGroups之间是多对多的关系,在代码中都用NSSet表示。

我使用什么来查询NSSet 中的群组成员,反之亦然? (我是 CoreData 的新手)

【问题讨论】:

  • 查询什么?你必须从什么开始(一个人/什么都没有?)你想找到什么?
  • 我正在尝试查看我的人是否已经属于某个组,如果没有添加他,或者忽略它

标签: ios core-data predicate foundation nsset


【解决方案1】:

使用 coredata,您可以轻松完成。假设我们在 Groups Table (group) 上有一个对象,你想让所有的朋友都属于 group,你可以这样做:

[组。 peopleInGroup allObjects]

更多详情:

  1. 通过标题获取组
NSError* error = nil;
NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init];
NSPredicate *predicate;
NSEntityDescription *entity;
NSArray *fetchedObjects;    
Group* group;    
entity = [NSEntityDescription
          entityForName:[NSString stringWithFormat:@"%@",[Group class]]
          inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"(title like[c] \"%@\")" ,title]];
[fetchRequest setPredicate:predicate];
fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects.count > 0) {
    group = [fetchedObjects lastObject];
}
return group;

}

  1. 获取组内所有好友

    NSMutableArray* friends = [NSMutableArray alloc] init]; [朋友addObjectsFromArray:[组。 peopleInGroup allObjects]];

【讨论】:

  • 您不必先执行 nsfetchrequest 之类的吗?
  • 是的,我们需要通过标题对组表进行NSFetchRequest,然后我们获取组的所有成员。没事吧?
猜你喜欢
  • 2016-06-07
  • 2021-12-05
  • 1970-01-01
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 2021-02-05
  • 2017-05-17
  • 1970-01-01
相关资源
最近更新 更多