你可能不知道的事(服务器返回 id)
最后更新于:2022-04-01 14:25:21
首先说一下id的问题
加入服务器就是给我们反馈了一个id:如下:
![id](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-04-07_57061102a4860.jpg "")
既然返回的是id,有些人就乱了阵脚,“这个是关键字,怎么来接?”
其实没事,他返回什么给我们,我们就拿什么来接,就行。看一下如何解决:
既然返回的是字典,那么久字典转模型,写个模型先:
模型.h
~~~
@interface ZYDemo : NSObject
@property(nonatomic,assign)int id;
@property(nonatomic,copy)NSString *message;
- (instancetype)initWithDict:(NSDictionary *)dict;
+ (instancetype)demoWithDict:(NSDictionary *)dict;
@end
~~~
模型.m
~~~
@implementation ZYDemo
- (instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init])
{
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
+ (instancetype)demoWithDict:(NSDictionary *)dict
{
return [[self alloc]initWithDict:dict];
}
@end
~~~
在viewControllder进行数据解析
~~~
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:@"http://localhost/demo.json"];
NSURLRequest *request1 = [NSURLRequest requestWithURL:url];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:10.0];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
ZYDemo *demo = [ZYDemo demoWithDict:result];
NSLog(@"%@",demo);
}];
}
~~~
看一下我们的模型是否出来了:
![id](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-04-07_57061102b4fde.jpg "")
看,我们一样能解决,不要去为难服务器的人