【问题标题】:Obj-C: UITableView update datasource cross-classObj-C:UITableView 更新数据源跨类
【发布时间】:2013-07-19 20:46:14
【问题描述】:

好的,现在的情况如何;我有一个名为 PlaylistController 的 UIViewController(带有一个用于整洁的自定义类)。这个控制器实现了 UITableViewDelegate 和 UITableViewDataSource 协议,并且相当粗略地用 NSMutableArray 中的一些基本信息填充了 UITableView:

播放列表控制器.h:

@interface PlaylistController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
    @public NSMutableArray* _playlists;
    @public NSMutableArray* _tracks;
}

@property (nonatomic, strong) IBOutlet UITableView *tableView;

播放列表控制器.m:

- (void)viewDidLoad
{
    [super viewDidLoad];

    tableView.delegate = self;
    tableView.dataSource = self;
    _playlists = [[NSMutableArray alloc] initWithObjects:@"Heyy", @"You ok?", nil];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section {
    return [_playlists count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"CellIdentifier";

    // Dequeue or create a cell of the appropriate type.
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    cell.textLabel.text = [NSString stringWithFormat:@"%@", [_playlists objectAtIndex:indexPath.row]];
    return cell;
}

效果很好,当我单击相应的选项卡以显示 UIViewController 时,它已全部填充。我的问题是在新数据可用时更改数据源。

考虑到新数据来自不同的类,我将如何更新数据源?单身人士?

【问题讨论】:

  • 有什么问题?您在_playlists_tracks 中设置新值,然后调用[tableView reloadData]; 让一切自动处理,不是吗?
  • 对不起,我可能不太清楚!更多的是如何我如何更新_playlists 从另一个类然后调用[tableView reloadData];
  • 你心目中的“其他类”是什么?如果PlaylistController 在屏幕上,则没有其他类可以控制;如果它不在屏幕上,viewWillAppear 可以负责更新。

标签: objective-c uiviewcontroller singleton uitableview


【解决方案1】:

将“播放列表”数组公开为视图控制器上的公共属性。实现一个自定义设置器,在设置时提示 tableview 重新加载数据:

@property (strong, nonatomic) NSArray* playlists;

...

@synthesize playlists=_playlists;

...

- (void) setPlaylists: (NSArray*) playlists
{
    _playlists = playlists;

    if ( self.isViewLoaded )
    {
        [self.tableView reloadData];
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多