iphone - 核心数据 NSSet 问题

标签 iphone objective-c ios core-data

我自动生成了核心数据 NSManagedObject 类,我想做的是显示某个人的所有电话号码。我试图在我的 TableView 类中显示它以填充表。

Person 和 Numbers 是一对多的关系,数字在我通过 addNumbersObject 方法做的集合中。我只是不明白如何在 fetchresultscontroller 中获取它并将它们显示在 TableView 中。

目前我正在抓取所有人。

有什么想法或建议吗?

核心数据类:

@class Number

@interface Person : NSManagedObject

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSSet *numbers;

@end

@interface Person (CoreDataGeneratedAccessors)

- (void)addNumbersObject:(Number *)value;
- (void)removeNumbersObject:(Number *)value;
- (void)addNumbers:(NSSet *)values;
- (void)removeNumbers:(NSSet *)values;

@end

TableView 类:

- (NSFetchedResultsController *)fetchedResultsController 
{    
    if (_fetchedResultsController != nil)
        return _fetchedResultsController;

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:_context];
    [fetchRequest setEntity:entity];

    NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
    [fetchRequest setFetchBatchSize:20];

    NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_context sectionNameKeyPath:nil cacheName:@"Root"];

    self.fetchedResultsController = theFetchedResultsController;
    _fetchedResultsController.delegate = self;

    [fetchRequest release];
    [theFetchedResultsController release];

    return _fetchedResultsController;      
}

最佳答案

尝试在您的 fetchRequest 上使用谓词。

根据你的问题,我不确定你是否想显示所有人的所有电话号码或你想要的格式,但这是获取一个人的所有电话号码的方法。

在一个 TableView 中获取一个特定人的所有电话号码:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Number" inManagedObjectContext:_context];

[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"person.name == %@", personName]]; //Assuming person.name is unique

然后根据需要对该人的电话号码进行排序。

关于iphone - 核心数据 NSSet 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9692997/

相关文章:

iPhone 发送邮件应用程序

objective-c - 内存管理与方法调用

objective-c - Cocoa:鼠标中键单击事​​件(全局)+手势API?

iphone - 下载多个图像并显示多个 UIImageView 的最佳方式是什么?

iphone - iOS5.0.1上的内存泄漏drawInRect

iphone - toSharedViewController 不重用现有的 Controller

ios - 在没有 Storyboard的情况下启动 ios 项目

ios - archiverootobject 和 unarchiverootobject 的有效文件路径

ios - 看不到属性错误

ios - 测试飞行 2.0.0 : "MyApp" isn't compatible with this device