深入解析设计模式中的装饰器模式在iOS应用开发中的实现

2020-01-15 13:22:37王冬梅

        currentAlbumData = nil;
    }

 

    // we have the data we need, let's refresh our tableview
    [dataTable reloaddata];
}


showDataForAlbumAtIndex: 从专辑数组中取出需要的专辑数据。当你需要显示新数据的时候,你只需要重载数据 (relaodData)。这是因为 UITableView 需要请求它的委托代理,像有多少 sections 将会在表单视图中显示,每个 section 中有多少行,每行看起来是什么样的。

 

在 viewDidLoad 中添加下面代码

复制代码
[self showDataForAlbumAtIndex:currentAlbumIndex];
当程序运行的时候它会加载当前的专辑信息。由于 currentAlbumIndex 的预设值为 0,所以会显示收藏中的第一张专辑信息。

 

构建并运行你的项目,你的程序会崩溃掉,在控制台会输入如下的异常:

设计模式,装饰器模式,iOS应用开发

 

出现什么问题了?你已经声明了 ViewController 中的 UItableView 的委托(delegate)和数据源(data source)。但是在这种情况下,你必需执行所有的必需方法─包含 tableView:numberOfRowsInsection:─你现在还没有它。

在 ViewContrller.m 的 @implementation 和 @end 的任何地方添加如下代码:

复制代码
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [currentAlbumData[@"titles"] count];
}

 

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    }

    cell.textLabel.text = currentAlbumData[@"titles"][indexPath.row];