1. 在model.h文件中声明属性(声明的属性与获取的字典中键(key)一致)
//属性名必须与字典里面的键(key)一样,KVC才会把值(value)传递进来
@property (nonatomic, copy) NSString *imageUrl;
@property (nonatomic, copy) NSString *contents;
@property (nonatomic, copy) NSString *date;
@property (nonatomic, copy) NSString *imageUrl;
@property (nonatomic, copy) NSString *contents;
@property (nonatomic, copy) NSString *date;
@property (nonatomic, assign) NSInteger
contentID;
2.在网络获取时用setValuesForKeysWithDictionary:把key-value一一对应
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
[manager GET:@"http://www.tingwen.me/akcms_category.php?id=1&page=1" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *dataArray = responseObject;
for (NSDictionary *dic in dataArray) {
//初始化model对象
NewsModel *newsModel = [[NewsModel alloc] init];
//从一个字典映射到一个对象里面,这是KVC里边的一个方法,不需要向以前一样把字典里边的键值取出来存在model属性里面
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
[manager GET:@"http://www.tingwen.me/akcms_category.php?id=1&page=1" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *dataArray = responseObject;
for (NSDictionary *dic in dataArray) {
//初始化model对象
NewsModel *newsModel = [[NewsModel alloc] init];
//从一个字典映射到一个对象里面,这是KVC里边的一个方法,不需要向以前一样把字典里边的键值取出来存在model属性里面
[newsModel setValuesForKeysWithDictionary:dic];
[self.datasource addObject:newsModel];
}
//数据封装完成后,需要刷新tableView显示新的数据内容
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// NSLog(@"error:%@", error);
}];
}
//数据封装完成后,需要刷新tableView显示新的数据内容
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// NSLog(@"error:%@", error);
}];
}
3.如果获取的文件中有关键字,用 setValue:(id)value forUndefinedKey:(NSString *)key把关键字key对应的value赋值给重新定义的属性:(用self.contentID代替系统关键字id)
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
if ([key isEqualToString:@"id"]) {
self.contentID = (NSInteger)value;
}
if ([key isEqualToString:@"id"]) {
self.contentID = (NSInteger)value;
}
}
本文将介绍如何利用Objective-C的KVC技术,结合AFNetworking库,在iOS应用中实现数据的高效绑定与网络请求操作。通过实例演示,展示如何在获取网络数据后,使用setValuesForKeysWithDictionary方法将JSON数据映射到模型对象中,同时处理特定关键字的赋值,确保数据的一致性和准确性。
746

被折叠的 条评论
为什么被折叠?



