开发者

Fetching data from a dictionary inside cellForRowAtIndexPath

开发者 https://www.devze.com 2023-02-12 13:11 出处:网络
I have a set of data inside a dictionary and inside - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

I have a set of data inside a dictionary and inside

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

method I want to fetch data from this dictionary. How can we fetch objects for each indexPath.row.

One way, I could think of is gett开发者_Go百科ing keys array and then fetch the object from this array based on indexPath.row and then use this key to fetch the dictionary object.

Please suggest.


dictionary is not an ordered collection like array, so the method you've suggested is probably the way to go... Depends on how do you want the data to be presented (sorted by keys/values).


It's not a good practice, because the order of the keys of a dictionary is not defined.

If your data must be a dictionary, then you must provide an explicit information that maps keys of the dictionary and the index path of the table.

For example, you can have another array in which the keys of the dictionary in sorted in the same order by which you would see your objects in the table.


How are your items sorted in the table? Is the order important? There isn't really an easy answer to this question. Are you sure you need to keep a dictionary of your data? The way I see, you have the following options:

  • call [dictionary allValues] to get an array of all values. You can then sort it the way you want and return the item at index indexPath.row. The draw back is you need to sort the array for each row which is not ideal if you have a lot of items. It might make your scrolling choppy.

  • keep a copy of a sorted array version of your dictionary and make sure to update it any time your dictionary is updated. This is better suited for a large data set that does not change often. You could wrap both your dictionary and array in a class that will take care of keeping the two in sync.

You'll need to weigh the drawbacks depending on what your data is like.

0

精彩评论

暂无评论...
验证码 换一张
取 消