171,.plist文件中字典数据转成程序模型

来源:互联网 发布:mysql中right函数 编辑:程序博客网 时间:2024/05/27 00:30


AppData.h:

#import <UIKit/UIKit.h>


@interface AppData : NSObject


@property(nonatomic,copy)NSString *name;

@property(nonatomic,copy)NSString *icon;


//readonly就只会生成settergetter方法,而不生成成员变量_image,所以,只能使用合成指令,定义_image

@property(nonatomic,strong,readonly)UIImage *image;


-(instancetype)initWithDic:(NSDictionary *)dic;

+(instancetype)appDataWithDic:(NSDictionary *)dic;

+(NSArray *)appList;


@end


AppData.m:

#import "AppData.h"

/*

 使用KVC的注意事项

 概念:全称(key value coding)键值编码,是一种简介修改/读取对象属性的一种方法

 1plist中的键值必须跟模型中的属性一致

 2,模型中的属性个数可以等于或多个plist中的属性个数

 */


@implementation AppData

//合成指令,主动指定属性使用的成员变量名称

@synthesize image = _image;


-(UIImage *)image{

    if (_image ==nil) {

        _image = [UIImageimageNamed:self.icon];

    }

    return  _image;

}


/**

 *  instancetype 主要用于在类方法实例化对象时,让编译器主动推断出对象的实际类型

 *

 */


-(instancetype)initWithDic:(NSDictionary *)dic{

    self = [superinit];

    if (self) {

//       赋值第一种方法:

//       self.name = dic[@"name"];

//       self.icon = dic[@"icon"];

//       赋值第二种方法

//       [self setValue:dic[@"name"] forKeyPath:@"name"];

//       self setValue:dic[@"icon"] forKeyPath:@"icon"];

//       第三种方法的本质就是第二种方法的封装

        [selfsetValuesForKeysWithDictionary:dic];

    }

    return self;

}


+(instancetype)appDataWithDic:(NSDictionary *)dic{

    return [[selfalloc]initWithDic:dic];

}


+(NSArray *)appList{

    NSString *path = [[NSBundlemainBundle]pathForResource:@"app"ofType:@".plist"];

    NSArray *arr = [NSArrayarrayWithContentsOfFile:path];

    NSMutableArray *dics = [[NSMutableArrayalloc]init];

    for (int i=0; i<arr.count; i++) {

        [dics addObject:[AppDataappDataWithDic:arr[i]]];

    }

    return dics;

}

@end


ViewController.h:

#import <UIKit/UIKit.h>

@class AppData;


@interface ViewController : UIViewController


@end


ViewController.m:

#import "ViewController.h"

#import "AppData.h"


@interface ViewController ()


@property(nonatomic,strong)NSArray *appList;


@end


@implementation ViewController


-(NSArray *)appList{

    if (_appList ==nil) {

        _appList = [AppDataappList];

    }

    return_appList;

}


-(void)viewDidLoad{

    [superviewDidLoad];

    for(int i =0;i <self.appList.count;i++){

        AppData *data = self.appList[i];

        NSLog(@"name = %@,icon = %@",data.name,data.icon);

    }

    

    for(int i =0;i <self.appList.count;i++){

        AppData *data = self.appList[i];

        UIImageView *image = [[UIImageViewalloc]initWithFrame:CGRectMake(0,0, 200, 200)];

        image.image =data.image;

        [self.viewaddSubview:image];

    }

}


@end




0 0