标签:
个人习惯,也可以不这样写
创建模型基类:
#import <Foundation/Foundation.h> @interface WJBaseModel : NSObject //将字典内的值赋给申明的相应属性 - (instancetype)initWithDict:(NSDictionary *)dict; + (instancetype)modelWithDict:(NSDictionary *)dict; @end
#import "WJBaseModel.h" @implementation WJBaseModel - (instancetype)initWithDict:(NSDictionary *)dict { self = [super init]; if (self) { } return self; } + (instancetype)modelWithDict:(NSDictionary *)dict { return [[self alloc]initWithDict:dict]; } @end
创建模型:
#import <Foundation/Foundation.h> #import "WJBaseModel.h" @interface AddressModel : WJBaseModel @property (nonatomic,copy)NSString *name;//名称 @property (nonatomic,copy)NSString *address;//地址 @property (nonatomic,copy)NSString *phoneNumber;//电话号码 @property (nonatomic,copy)NSString *defaultAddress;//默认地址 @property (nonatomic,copy)NSString *addressDetail;//详细地址 @property (nonatomic,copy)NSString *num;//邮编 @end
#import "AddressModel.h" @implementation AddressModel - (instancetype)initWithDict:(NSDictionary *)dict { self = [super initWithDict:dict]; if (self) { self.name = dict[@"name"]; self.address = dict[@"address"]; self.phoneNumber = dict[@"phoneNumber"]; self.defaultAddress = dict[@"defaultAddress"]; self.addressDetail = dict[@"addressDetail"]; self.num = dict[@"num"]; } return self; } @end
注意:上面字典的键要和传入字典的键相同
使用:
1.添加数据:(假数据)
[self initDataSource:@[@{@"name":@"黄智擒", @"phoneNumber":@"123456789", @"address":@"时代荆轲名媛 17-1102", @"defaultAddress":@"0", @"addressDetail":@"addressDetail", @"num":@"987654321"}, @{@"name":@"黄智擒", @"phoneNumber":@"123456789", @"address":@"时代荆轲名媛 17-1102", @"defaultAddress":@"1", @"addressDetail":@"addressDetail", @"num":@"987654321"}, @{@"name":@"黄智擒", @"phoneNumber":@"123456789", @"address":@"时代荆轲名媛 17-1102", @"defaultAddress":@"0", @"addressDetail":@"addressDetail", @"num":@"987654321"}, @{@"name":@"黄智擒", @"phoneNumber":@"123456789", @"address":@"时代荆轲名媛 17-1102", @"defaultAddress":@"0", @"addressDetail":@"addressDetail", @"num":@"987654321"}, @{@"name":@"黄智擒", @"phoneNumber":@"123456789", @"address":@"时代荆轲名媛 17-1102", @"defaultAddress":@"0", @"addressDetail":@"addressDetail", @"num":@"987654321"}, @{@"name":@"黄智擒", @"phoneNumber":@"123456789", @"address":@"时代荆轲名媛 17-1102", @"defaultAddress":@"0", @"addressDetail":@"addressDetail", @"num":@"987654321"}]];
2.将模型添加到可变数组上(只有一个模型的话就用字典算了)
#pragma mark - 模型数据 - (void)initDataSource:(NSArray *)dicArray { _dataSource = [[NSMutableArray alloc]init];for (NSDictionary *dic in dicArray) { AddressModel *model = [AddressModel modelWithDict:dic]; [_dataSource addObject:model]; } }
3.在UITableView中使用(补充使用)
cell中申明模型属性
@property (nonatomic,strong)AddressModel *model;
重写set方法,添加模型数据到相应的控件上显示
-(void)setModel:(AddressModel *)model{ _model = model; _nameAndNum.text = [NSString stringWithFormat:@"%@ %@",model.name,model.phoneNumber]; _address.text = [NSString stringWithFormat:@"%@ %@",model.address,model.addressDetail]; }
效果图:
标签:
原文地址:http://www.cnblogs.com/hxwj/p/4549973.html