首页 > 代码库 > iOS开发项目篇—24字典转模型
iOS开发项目篇—24字典转模型
iOS开发项目篇—24字典转模型
一、直接使用字典转模型
1.微博数据转模型示意图:
2.字典转模型
查询字段:
新建需要的数据模型:
字典转模型相关的代码:
YYUserModel.h文件
1 // 2 // YYUserModel.h 3 // 4 5 #import <Foundation/Foundation.h> 6 7 @interface YYUserModel : NSObject 8 9 /** string 友好显示名称*/10 @property(nonatomic,copy)NSString *name;11 12 /**string 用户头像地址(中图),50×50像素*/13 @property(nonatomic,copy)NSString *profile_image_url;14 15 //接口16 +(instancetype)userModelWithDict:(NSDictionary *)Dict;17 @end
YYUserModel.m文件
1 // 2 // YYUserModel.m 3 // 4 5 #import "YYUserModel.h" 6 7 @implementation YYUserModel 8 +(instancetype)userModelWithDict:(NSDictionary *)Dict 9 {10 YYUserModel *model=[[self alloc]init];11 model.name=Dict[@"name"];12 model.profile_image_url=Dict[@"profile_image_url"];13 return model;14 }15 @end
YYStatusModel.h文件
1 // 2 // YYStatusModel.h 3 // 4 5 #import <Foundation/Foundation.h> 6 #import "YYUserModel.h" 7 8 @interface YYStatusModel : NSObject 9 /** string 微博创建时间*/10 @property(nonatomic,copy)NSString *created_at;11 12 /** string 字符串型的微博ID*/13 @property(nonatomic,copy)NSString *idstr;14 15 /** string 微博信息内容*/16 @property(nonatomic,copy)NSString *text;17 18 /** string 微博来源*/19 @property(nonatomic,copy)NSString *source;20 21 /** object 微博作者的用户信息字段 详细*/22 @property(nonatomic,strong)YYUserModel *user;23 24 /** object 被转发的原微博信息字段,当该微博为转发微博时返回 详细*/25 @property(nonatomic,strong)YYStatusModel *retweeted_status;26 27 /** int 转发数*/28 @property(nonatomic,assign)int *reposts_count;29 30 /** int 评论数*/31 @property(nonatomic,assign)int *comments_count;32 33 /** int 表态数*/34 @property(nonatomic,assign)int *attitudes_count;35 36 /** object 微博配图地址。多图时返回多图链接。无配图返回“[]” 数组里面都是HMPhoto模型*/37 @property(nonatomic,copy)NSArray *pic_urls;38 39 //接口40 +(instancetype)statusModelWithDict:(NSDictionary *)Dict;41 42 @end
YYStatusModel.m文件
1 // 2 // YYStatusModel.m 3 // 4 5 #import "YYStatusModel.h" 6 7 @implementation YYStatusModel 8 +(instancetype)statusModelWithDict:(NSDictionary *)Dict 9 {10 YYStatusModel *model=[[self alloc]init];11 model.text=Dict[@"text"];12 13 model.user=[YYUserModel userModelWithDict:Dict[@"user"]];14 15 //嵌套模型16 NSDictionary *retweetedDict = Dict[@"retweetedDict"];17 if (retweetedDict) {18 model.retweeted_status=[YYStatusModel statusModelWithDict:retweetedDict];19 }20 return model;21 }22 @end
YYPhotoModel.h文件
1 // 2 // YYPhotoModel.h 3 // 4 5 #import <Foundation/Foundation.h> 6 7 @interface YYPhotoModel : NSObject 8 /** 缩略图 */ 9 @property (nonatomic, copy) NSString *thumbnail_pic;10 @end
在“首页”中使用模型为cell填充数据的代码:
YYHomeTableViewController.m文件
1 // 2 // YYHomeTableViewController.m 3 // 4 5 #import "YYHomeTableViewController.h" 6 #import "YYOneViewController.h" 7 #import "YYTitleButton.h" 8 #import "YYPopMenu.h" 9 #import "YYAccountModel.h" 10 #import "YYAccountTool.h" 11 #import "AFNetworking.h" 12 #import "UIImageView+WebCache.h" 13 #import "YYUserModel.h" 14 #import "YYStatusModel.h" 15 16 @interface YYHomeTableViewController ()<YYPopMenuDelegate> 17 @property(nonatomic,assign)BOOL down; 18 @property(nonatomic,strong)NSMutableArray *statuses; 19 @end 20 21 @implementation YYHomeTableViewController 22 23 - (id)initWithStyle:(UITableViewStyle)style 24 { 25 self = [super initWithStyle:style]; 26 if (self) { 27 // Custom initialization 28 } 29 return self; 30 } 31 32 - (void)viewDidLoad 33 { 34 [super viewDidLoad]; 35 36 //设置导航栏内容 37 [self setupNavBar]; 38 39 //加载最新数据 40 [self loadNewStatus]; 41 42 } 43 44 /**加载最新微博数据*/ 45 -(void)loadNewStatus 46 { 47 //1.获得请求管理者 48 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; 49 50 //2.封装请求参数 51 52 NSMutableDictionary *params=[NSMutableDictionary dictionary]; 53 params[@"access_token"] =[YYAccountTool accountModel].access_token; 54 //设置请求返回3天数据 55 params[@"count"]=@12; 56 57 58 //3.发送Post请求 59 // url:https://api.weibo.com/2/statuses/home_timeline.json 60 [mgr GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary*accountDict) { 61 62 YYLog(@"请求成功--%@",accountDict[@"statuses"]); 63 // self.statuses=accountDict[@"statuses"]; 64 65 self.statuses = [NSMutableArray array]; 66 67 // 微博字典 -- 数组 68 NSArray *statusDictArray = accountDict[@"statuses"]; 69 for (NSDictionary *statusDict in statusDictArray) { 70 YYStatusModel *status = [YYStatusModel statusModelWithDict:statusDict]; 71 [self.statuses addObject:status]; 72 } 73 74 75 //重新刷新表格 76 [self.tableView reloadData]; 77 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 78 YYLog(@"请求失败"); 79 }]; 80 81 } 82 /**设置导航栏内容*/ 83 -(void)setupNavBar 84 { 85 self.navigationItem.leftBarButtonItem=[UIBarButtonItem itemWithImageName:@"navigationbar_friendsearch" highImageName:@"navigationbar_friendsearch_highlighted" target:self action:@selector(friendsearch)]; 86 self.navigationItem.rightBarButtonItem=[UIBarButtonItem itemWithImageName:@"navigationbar_pop" highImageName:@"navigationbar_pop_highlighted" target:self action:@selector(pop)]; 87 88 //设置导航栏按钮 89 YYTitleButton *titleButton=[[YYTitleButton alloc]init]; 90 //设置文字 91 [titleButton setTitle:@"首页" forState:UIControlStateNormal]; 92 //设置图标 93 [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal]; 94 //设置背景 95 [titleButton setBackgroundImage:[UIImage resizedImage:@"navigationbar_filter_background_highlighted"] forState:UIControlStateHighlighted]; 96 97 //设置尺寸 98 titleButton.width=100; 99 titleButton.height=35;100 //监听按钮的点击事件101 [titleButton addTarget:self action:@selector(titleButtonClick:) forControlEvents:UIControlEventTouchUpInside];102 self.navigationItem.titleView=titleButton;103 }104 -(void)titleButtonClick:(UIButton *)titleButton105 {106 107 [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_up"] forState:UIControlStateNormal];108 109 UITableView *tableView=[[UITableView alloc]init];110 [tableView setBackgroundColor:[UIColor yellowColor]];111 YYPopMenu *menu=[YYPopMenu popMenuWithContentView:tableView];112 [menu showInRect:CGRectMake(60, 55, 200, 200)];113 menu.dimBackground=YES;114 115 menu.arrowPosition=YYPopMenuArrowPositionRight;116 menu.delegate=self;117 }118 119 120 #pragma mark-YYPopMenuDelegate121 //弹出菜单122 -(void)popMenuDidDismissed:(YYPopMenu *)popMenu123 {124 YYTitleButton *titleButton=(YYTitleButton *)self.navigationItem.titleView;125 [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal];126 }127 -(void)pop128 {129 YYLog(@"---POP---");130 }131 -(void)friendsearch132 {133 //跳转到one这个子控制器界面134 YYOneViewController *one=[[YYOneViewController alloc]init];135 one.title=@"One";136 //拿到当前控制器137 [self.navigationController pushViewController:one animated:YES];138 139 }140 141 #pragma mark - Table view data source142 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section143 {144 return self.statuses.count;145 }146 147 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath148 {149 static NSString *ID = @"cell";150 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];151 if (!cell) {152 cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];153 }154 // cell.textLabel.text = [NSString stringWithFormat:@"%d----首页测试数据", indexPath.row];155 156 //取出这行对应的微博字典数据157 // NSDictionary *statusDict = self.statuses[indexPath.row];158 // cell.textLabel.text=statusDict[@"text"];159 // 160 // //取出user字典数据161 // NSDictionary *userDict=statusDict[@"user"];162 // cell.detailTextLabel.text=userDict[@"name"];163 // 164 // //下载头像图片165 // NSString *imageUrlStr=userDict[@"profile_image_url"];166 // [cell.imageView setImageWithURL:[NSURL URLWithString:imageUrlStr] placeholderImage:[UIImage imageWithName:@"avatar_default_small"]];167 168 //取出这行对应的微博字典数据,转换为数据模型169 YYStatusModel *status=self.statuses[indexPath.row];170 cell.textLabel.text=status.text;171 cell.detailTextLabel.text=status.user.name;172 NSString *imageUrlStr=status.user.profile_image_url;173 [cell.imageView setImageWithURL:[NSURL URLWithString:imageUrlStr] placeholderImage:[UIImage imageWithName:@"avatar_default_small"]];174 175 return cell;176 }177 178 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath179 {180 //点击cell的时候,跳到下一个界面181 UIViewController *newVc = [[UIViewController alloc] init];182 newVc.view.backgroundColor = [UIColor redColor];183 newVc.title = @"新控制器";184 [self.navigationController pushViewController:newVc animated:YES];185 }186 187 @end
实现查看:
3.补充:
下载图片可能会耗费大量的内存,当接收到内存警告的时候需要做出一定的处理。
YYAppDelegate.m文件
1 #import "YYAppDelegate.h" 2 #import "YYOAuthViewController.h" 3 #import "YYControllerTool.h" 4 #import "YYAccountTool.h" 5 #import "YYAccountModel.h" 6 #import "SDWebImageManager.h" 7 #import "SDImageCache.h" 8 9 @implementation YYAppDelegate10 11 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions12 {13 14 //1.创建窗口15 self.window=[[UIWindow alloc]init];16 self.window.frame=[UIScreen mainScreen].bounds;17 18 //获取文件夹19 // NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];20 // //获取写入的文件路径21 // NSString *filePath=[doc stringByAppendingPathComponent:@"account.plist"];22 // //获取信息,以进行判断23 // NSDictionary *account=[NSDictionary dictionaryWithContentsOfFile:filePath];24 25 //2.显示窗口(主窗口)26 [self.window makeKeyAndVisible];27 28 //3.设置窗口的根控制器29 YYAccountModel *account=[YYAccountTool accountModel];30 31 if (account) { // 存在成功授权的账号信息32 [YYControllerTool chooseRootViewController];33 }else //没有登陆过34 {35 self.window.rootViewController=[[YYOAuthViewController alloc]init];36 }37 38 return YES;39 }40 41 - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application42 {43 // 赶紧清除所有的内存缓存44 [[SDImageCache sharedImageCache] clearMemory];45 46 // 赶紧停止正在进行的图片下载操作47 [[SDWebImageManager sharedManager] cancelAll];48 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。