我目前被困在如何最好地查找和传递单击的表格 View 行的 ID。我想知道实现这一目标的最佳实践是什么。
tableview
. 地址加上一个唯一的 ID。
和地址,但我不想显示唯一 ID。
现在来了我的问题 : 如果我没有显示唯一 ID,如何根据点击的行再次找到该 ID?有没有分配隐藏字段的方法?我想通过 POST 发送唯一 ID返回网络服务器。
到目前为止,我一直在调查的方向是...
NSDictionary
并将单击的 tableview 行匹配回它以获取 ID。 您认为从单击的 tableview 行中获取相应 ID 的最佳方法是什么。
非常感谢您的时间。
最佳答案
这就是你可以做到这一点的方法
调用您的网络服务并获取 json。解析 json 并继续将对象添加到 NSMutableArray 中,比如 itemList。
创建一个模型类,比如 Itemdesc,它将有 3 个字段名称、地址和 ID。
当您解析 json 时,将每个单独的产品提取到上面定义的项目模型对象中,并将其添加到 itemList 数组中。
它可能是这样的:
NSArray *responseArray = responsefromService;
For(int i=0;i<responseArray.count;i++)
{
//Parse your object here
NSDictionary *currentItem = [responseArray objectAtIndex:i];
Itemdesc *itemObject = [[Itemdesc alloc] init];
itemObject.name = [currentItem objectForKey:@"name"];
itemObject.address = [currentItem objectForKey:@"address"];
itemObject.ID = [currentItem objectForKey:@"ID"];
[itemList addObject:itemObject];
itemObject=nil;
}
现在将此数组作为对象传递给 tableView 以获取行数,并在 cellForRowAtIndexPath 中获取您的行对象,如下所示:
Itemdesc *currentIndexObj = [itemList objectAtIndex:indexpath.row];
cell.name.text = currentIndexObj.name;
cell.address.text = currentIndexObj.address;
这将在您的 tableViewCell 中显示您的姓名和地址。
要在选择一行时获取 ID,请在您的 didSelectRowAtIndexPath 中编写以下代码:
Itemdesc *currentIndexObj = [itemList objectAtIndex:indexpath.row];
NSString *ID = currentIndexObj.ID;
NSLog(@"ID value: %@", ID);
你有你的ID,执行你想要执行的任何操作。
模型类只不过是一个普通的类本身。
创建模型类的代码:
转到文件 -> 新建 -> 文件 ->iOS-> 源 -> CocoaTouch 类
选择下一个并给 Class 一个名称 ItemDesc 并使其成为 NSObject 的子类。在您的项目中,您将获得文件 Itemdesc.h 和 Itemdesc.m
Itemdesc.h 文件:
#import <Foundation/Foundation.h>
@interface Itemdesc : NSObject
@property(nonatomic,strong) NSString *name;
@property(nonatomic,strong) NSString *address;
@property(nonatomic,strong) NSString *itemID;
@结尾
无需对 .m 文件进行任何更改。
就是这样。在您的 tableView 存在的类中导入标题并且事情会起作用。
json结构:
[
{
"name" : "John",
"address" : "ny",
"ID" : "xyz"
},
{
"name" : "Jane",
"address" : "dc",
"ID" : "pqr"
}
]
关于ios - 匹配单击的 TableView 行(字符串)以找到对应的唯一 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29802020/