zoukankan      html  css  js  c++  java
  • IOS 字典转模型

    用模型存放字典上的内容,方便使用

    一、创建类MJHero

    1、在头文件声明属性,声明对象方法,类方法 

    #import <Foundation/Foundation.h>

    @interface MJHero : NSObject
    @property (nonatomic, copy) NSString *name;
    @property (nonatomic, copy) NSString *icon;
    @property (nonatomic, copy) NSString *intro;

    + (instancetype)heroWithDict:(NSDictionary *)dict;
    - (instancetype)initWithDict:(NSDictionary *)dict;
    @end

    2、在.m实现方法

    #import "MJHero.h"

    @implementation MJHero
    + (instancetype)heroWithDict:(NSDictionary *)dict
    {
        return [[self alloc] initWithDict:dict];
    }

    - (instancetype)initWithDict:(NSDictionary *)dict
    {
        if (self = [super init]) {
            [self setValuesForKeysWithDictionary:dict];
        }
        return self;
    }
    @end

    二、在ViewController.m中添加数组和get方法

    #import "MJViewController.h"
    #import "MJHero.h"

    @property (nonatomic, strong) NSArray *heros;

    - (NSArray *)heros
    {
        if (_heros == nil) {
            // 初始化
            // 1.获得plist的全路径
            NSString *path = [[NSBundle mainBundle] pathForResource:@"heros.plist" ofType:nil];
            
            // 2.加载数组
            NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
            
            // 3.将dictArray里面的所有字典转成模型对象,放到新的数组中
            NSMutableArray *heroArray = [NSMutableArray array];
            for (NSDictionary *dict in dictArray) {
                // 3.1.创建模型对象
                MJHero *hero = [MJHero heroWithDict:dict];
                
                // 3.2.添加模型对象到数组中
                [heroArray addObject:hero];
            }
            
            // 4.赋值
            _heros = heroArray;
        }
        return _heros;
    }

     
  • 相关阅读:
    电话号码的字母组合(力扣第17题)
    太平洋大西洋水流问题(力扣第417题)
    被围绕的区域(力扣第130题)
    ZooKeeper的本地安装和分布式安装
    朋友圈(力扣第547题)
    岛屿数量(力扣第200题)
    岛屿的最大面积(力扣第695题)
    再论力扣第279题--完全平方数
    .net core使用CSRedisCore连接哨兵集群,并用作redis使用分布式缓存。
    使用docker搭建reids主从,哨兵。
  • 原文地址:https://www.cnblogs.com/zhongxuan/p/4858987.html
Copyright © 2011-2022 走看看