简体   繁体   中英

How to map UITableView cell to a remote database backend?

I'm making a simple To-Do list app for the iPhone with a rails backend.

So far, I can pull all the tasks in a To-Do list from the web app, parse the JSON, and insert it into the UITableView.

The json response from rails:

[
  {"id":1,"name":"Buy bread"},
  {"id":8,"name":"Get gas"},
  {"id":14,"name":"Call John"}
]

In the UITableView, a row for each task, the textLabel of the cell is the name of the task:

在此输入图像描述

The problem I'm having now is how to associate the cell with the record id of the task.

Two tasks can have the same name, so I can't just get the id from the hash based only on the name.

I need the record id, so I can post back to the rails app, after the user edits the UItableView (deletes a task for example).

Is there a property I can set on the cell? I feel like I'm missing something obvious. This is my first iPhone app, so please be gentle, hehe.

How are you getting the JSON array to an Objective-C array for use in the table? You'll have to do that again for the ID of the task, and in your - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath method use something like theID = [idArray objectAtIndex:indexPath.row];

The better solution would be to maintain a proper data model on the client. You could use the JSON as your model, but Core Data is a bit more robust. What you'd want is to have your controller associate what it knows about the view with what it knows about the model. For instance, if you use didSelectRowAtIndexPath: You'd want to use this index path to map to your model.

Your solution of setting a property on a cell which allows a client of your view to query your data model is in violation of the rules of the MVC paradigm. It couples your view to your model which isn't great.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM