【发布时间】:2013-09-08 03:23:34
【问题描述】:
编辑:有人有关于这个主题的有用链接吗?我的意思是编写可重用代码和“抽象”的良好做法?
tl;dr - 阅读此评论 Abstracting UIViewController like Cocoa ones
我有 3 个UITableViewController:
CategoriesViewControllerRecipesViewControllerIngredientsViewController
它们是按层次排序的。下面是一个层次结构的例子:
- 甜点(类)
- 布朗尼(配方)
- 牛奶(成分)
- 巧克力(成分)
- 黄油(成分)
- 布朗尼(配方)
其中每一个都具有与其他类似的功能。 例如,它们都有排序(移动行)、删除、添加(呈现模态视图)等。
目前,我已经为每个视图控制器重复了所有代码,以自定义与每个视图控制器相关的部分。例如,它们都有一个像这样的实例变量:
CategoriesViewController.m:
@implementation CategoriesViewController {
NSMutableArray *categories;
}
RecipesViewController.m:
@implementation RecipesViewController {
NSMutableArray *recipes;
}
IngredientsViewController.m:
@implementation IngredientsViewController {
NSMutableArray *ingredients;
}
因为我认为有更好的方法来组织这个视图控制器,所以我尝试创建一个 MyListViewController.h 的骨架:
@interface MyListViewController : UITableViewController
@property (nonatomic, strong) NSMutableArray *list;
@end
MyListViewController.m:
@implementation MyListViewController
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_list count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ListCell"];
id currentObject = [_list objectAtIndex:indexPath.row];
cell.textLabel.text = [currentObject valueForKey:@"name"];
return cell;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// get item to delete
id object = [_list objectAtIndex:indexPath.row];
// remove it from list
[_list removeObjectAtIndex:indexPath.row];
// call callback
[self didFinishDeletingItem:object];
// delete row from tableview
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
- (void)didFinishDeletingItem:(id)item
{
}
这样,一旦我对它进行了子类化,我只需将list ivar 分配给我的数据结构。我什至可以覆盖 didFinishDeletingItem: 之类的方法来自定义每个控制器的行为。
因为这是我第一次以这种方式使用编写和组织代码的最佳实践,所以我很想知道您的意见,以及哪些是抽象类以正确地重用它们的最佳方法DRY 原则。
【问题讨论】:
标签: iphone ios objective-c design-patterns uiviewcontroller