我正在尝试以编程方式设置 NSArrayController
以使用 Core Data。
我知道我的核心数据存储有内容,因为我可以通过托管对象上下文手动检索对象。我将 NSArrayController
连接到相同的托管对象上下文,然后将 NSTableColumn
的值参数绑定(bind)到 NSArrayController
。
我要求 NSArrayController
获取数据,但它返回一个空数组。
对我可能做错了什么有什么建议吗?
界面
@interface MTTableViewController : NSObject <NSTableViewDelegate, NSTableViewDataSource>
{
NSMutableArray *tableData;
MTTableCell *tableCell;
IBOutlet NSTableColumn *tableColumn;
NSArrayController *dataController;
}
实现
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
dataController = [[NSArrayController alloc] init];
[dataController setManagedObjectContext:[[NSApp delegate] managedObjectContext]];
[dataController setEntityName:@"Track"];
[dataController setAutomaticallyPreparesContent:YES];
[dataController fetch:self];
NSArray *content = [dataController arrangedObjects];
NSLog(@"Count :%i", (int)[content count]); //Outputs 0
tableCell = [[MTTableCell alloc] initTextCell:@""];
[tableColumn setDataCell:tableCell];
}
return self;
}
最佳答案
fetch:
不等待数据加载,而是立即返回。
这在支持绑定(bind)的环境中是有意义的。您通常有一个绑定(bind)到数组 Controller 的 TableView ,它会在 Controller 内容更改时更新。
在这种情况下,您可以观察 Controller 的 arrangedObjects
的变化:
[self.arrayController addObserver:self forKeyPath:@"arrangedObjects" options:NSKeyValueObservingOptionNew context:NULL];
然后:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
NSLog(@"Data: %@", self.arrayController.arrangedObjects);
}
关于objective-c - 如何使用核心数据设置 NSArrayController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8229248/