Search code examples
iphoneobjective-cioscocoa-touchios5

Refreshing UItableView Data from a frequently changing NSArray


i've a UITableView and I'm reading a data from a web service. the data from the web service may change at any time, so i have to refresh my data periodically.

i've managed to refresh the data and store it in an NSArray, but the UITableView won't display those data.

i tried

[myTableView reloadData];

but it have no effect.

EDIT:

i've implemented all the methods to load the data from an NSArray to the UiTableView. this works when the NSArray is initialized in the ViewDidLoad.

but if the NSArray changed while the application is running, the UITableView Will not display those changes.


Solution

  • You need to implement the UITableViewDataSource delegate protocol, specifically - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    Use this method to set up the cell. You can use the row property of indexPath to determine which cell you are setting up and provide it with data from your array.

    For example

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    id item = [dataArray objectAtIndex:indexPath.row]; // Whatever data you're storing in your array
    cell.textLabel.text = [item description]; // Substitute this for whatever you want to do with your cell.
    }
    

    EDIT:

    reloadData should call
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView and
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    to see if there are any cells to be drawn. Make sure you implement these methods as well and return non-zero values or your table view won't try to draw any cells and - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath won't be called.

    Parse
    You may also be interested in this library which claims to make remote data-driven tables a lot simpler.