数据解析的基类

来源:互联网 发布:网络尖兵下载 编辑:程序博客网 时间:2024/05/16 06:32

已经写好了,可以直接用,用的时候只需要写网址就好,model也已经写好了

ZCGBaseModel.h

#import <Foundation/Foundation.h>@interface ZCGBaseModel : NSObject+(NSMutableArray *)baseModelByArr:(NSArray *)arr;

ZCGBaseModel.m

#import "ZCGBaseModel.h"@implementation ZCGBaseModel+(NSMutableArray *)baseModelByArr:(NSArray *)arr{    // 创建一个可变数组    NSMutableArray *array=[NSMutableArray array];    // 传过来的数组是数组套字典结构,对数组进行遍历    for (NSDictionary *dic in arr) {        // 创建对象,对象的内容以字典为依据        id model =[[self class] baseModelWithDic:dic];        //把对象加到数组里        [array addObject:model];    }    return array;}// 写一个遍历构造器,通过构造器创建对象,并把字典作为参数传到方法里+(instancetype)baseModelWithDic:(NSDictionary *)dic{    //通过self class可以找到调用方法的类,然后通过类去调用方法alloc,从而实现创建的操作    id model = [[[self class] alloc] initWithDic:dic];    return model;}// 便利构造器封装了初始化方法,所以还要写一个初始化方法-(instancetype)initWithDic:(NSDictionary *)dic{    self=[super init];    if (self) {        // 字典对对象进行赋值的操作        [self setValuesForKeysWithDictionary:dic];    }    return self;}-(void)setValue:(id)value forUndefinedKey:(NSString *)key{}

BBSModel.h

#import "ZCGBaseModel.h"@interface BBSModel : ZCGBaseModel@property(nonatomic,copy)NSString *title;@property(nonatomic,copy)NSString *reply;@end

ViewController.m

#import "ViewController.h"#import "BBSModel.h"@interface ViewController ()@property(nonatomic,retain)NSMutableArray *arr;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    [self createData];}-(void)createData{    NSString *strUrl=@"http://lib.wap.zol.com.cn/bbs/ios/getHotBook.php?page=1&userid=&vs=442";    NSURL *url=[NSURL URLWithString:strUrl];    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];    NSURLSession *session=[NSURLSession sharedSession];    NSURLSessionTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];        NSArray *arr1=dic[@"hotList"];        self.arr = [BBSModel baseModelByArr:arr1];        NSLog(@"%@",self.arr);    }];    [task resume];}
0 0
原创粉丝点击