Obj-C:UITableView更新数据源跨类

时间:2013-07-19 20:46:14

标签: objective-c uiviewcontroller singleton uitableview

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

PlaylistController.h:

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

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

PlaylistController.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时,它已全部填充。我的问题是在新数据可用时更改数据源。

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

1 个答案:

答案 0 :(得分:0)

将“播放列表”数组公开为视图控制器上的公共属性。实现一个自定义setter,在set:

时提示tableview重新加载Data
@property (strong, nonatomic) NSArray* playlists;

...

@synthesize playlists=_playlists;

...

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

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