我在 Apple Watch 应用程序中使用了 NSFetchedResultController 和 WKInterfaceTable。确实不如UITableViewController方便,但是非常可行。我没有任何性能问题,即使在加载 20+ 行时(没有尝试 80-90)。当然这是在模拟器中,所以我不知道设备本身会如何表现。
插入、更新和删除你必须自己实现,但没那么难。
下面是我在InterfaceController中的部分代码,以插入行为例,但编辑和删除并不难:
界面
...
@property (weak, nonatomic) IBOutlet WKInterfaceTable *interfaceTable;
@property(strong, nonatomic) NSFetchRequest *fetchRequest;
@property(strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
@property(strong, nonatomic) NSMutableArray *data;
...
实施
获取和往常一样,只是我们没有为结果控制器分配委托,而是直接保存数据:
self.fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"YourModel" inManagedObjectContext:self.managedObjectContext];
self.fetchRequest.entity = entityDescription;
[self.fetchRequest setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:YES]]];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:self.fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
[self.fetchedResultsController performFetch:&error];
self.data= self.fetchedResultsController.fetchedObjects;
然后我使用一个函数loadTableData:
- (void)loadTableData {
[self.interfaceTable setNumberOfRows:[[self data] count] withRowType:@"YourCustomCell"];
[self.interfaceTable insertRowsAtIndexes:[NSIndexSet indexSetWithIndex:[[self data] count]] withRowType:@"YourRowType"];
for (int i = 0; i<[[self data] count];i++)
[self configureRowControllerAtIndex:i];
}
调用configureRowControllerAtIndex,一个填充一行的函数(我有两个标签):
- (void)configureRowControllerAtIndex:(NSInteger)index {
WKTableVIewRowController *listItemRowController = [self.interfaceTable rowControllerAtIndex:index];
[listItemRowController setTitle:[[self.data[index] title] integerValue]];
[listItemRowController setDescription:[self.data[index] description]];
}
插入新行时,只需在数据数组中手动添加managedObjectContext和:
// Add in managedObjectContext
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"YourModel" inManagedObjectContext:self.managedObjectContext];
YourModel *newRow = [[YourModel alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:nil];
// Add in data array
[self.data addObject:newRow];
并定期保存 managedObjectContext:
if (![self.managedObjectContext save:&error]) {
if (error) {
NSLog(@"Unable to save changes.");
NSLog(@"%@, %@", error, error.localizedDescription);
}
}