iOS之OC面向对象的建模:MVC

  • 实例化一个类:从plist文件抽取出类
@interface Person : NSObject

// 实例化对象(抽取出类)
@property (nonatomic, strong)NSString *name;
@property (nonatomic, strong)NSString *tel;
@property (nonatomic, strong)NSString *pic;

// 遍历初始化(参数是字典)
- (Person *)initWithDictionary:(NSDictionary *)dic;
+ (Person *)personWithDictionary:(NSDictionary *)dic;
@end
  • 使用字典作为自定义构造器的参数
#import "Person.h"

@implementation Person

// 自定义构造器
- (Person *)initWithDictionary:(NSDictionary *)dic
{
    if (self = [super init])
    {
        _name = dic[@"name"];
        _tel = dic[@"tel"];
        _pic = dic[@"pic"];
    }
    return self;
    
}

// 类工厂方法
+ (Person *)personWithDictionary:(NSDictionary *)dic
{
    return [[self alloc] initWithDictionary:dic];
    
}

@end
  •  存储对象的不仅仅可以是该类的指针
  •  把plist文件实例化最大的好处:数据处理创建对应对象,取值操作数据变得很easy
  •  实例化对象后,不需要考虑plist文件格式,只需要找对应实例取值就OK
  •  注意:
  •  因为所有的数据都被实例化到一个集合,如果分区的话,每个区取值都是从0开始

  •  因此这里使用实例化对象是得不到分区以及分区索引的:使用属性都在一个集合

  •  字典有时候更适合,不要思维定式为集合首选(面向对象的思想)

  •  // 初始化动态集合
        self.arrPerson = [NSMutableArray array];
        // 实例化该plist抽取出类的对象:通过字典赋值
        for (NSString *key in self.arrSection)
        {
            // 遍历字典所有value得到的是集合
            
            for (NSDictionary *dic in self.dicData[key])
            {
                // 遍历该集合得到的每个人对象的信息(字典)
                集合存储对象(对象的存储不仅仅局限于该类的指针)
                [self.arrPerson addObject:[Person personWithDictionary:dic]];
            }
        }
        // 测试数据存在
        NSLog(@"存储的任意对象key为name = %@", [self.arrPerson[12] name]);
        










原文地址:https://www.cnblogs.com/tmf-4838/p/5294036.html