iOS 数据模型基类

作者: 帅只是表象 | 来源:发表于2016-04-22 17:50 被阅读1581次

    在项目中,我们常常会用到数据模型,我们会用它来接收数据或者保存数据。你有没有觉的每次使用的时候都很麻烦呢,要写很多代码?不要紧,我们可以写一个数据模型的基础类,每次创建的model类继承它就可以方便使用了,是不是很简单呢!

    BaseModel.h

    #import <Foundation/Foundation.h>
    #import <objc/runtime.h>
    
    @interface BaseModel : NSObject
    
    //接收数据使用
    - (id)initWithDictionary:(NSDictionary*)jsonDic;
    
    //归档专用
    - (id)initWithCoder:(NSCoder *)aDecoder;
    - (void)encodeWithCoder:(NSCoder *)aCoder;
    
    @end
    

    BaseModel.m

    #import "BaseModel.h"
    
    @implementation BaseModel
    
    - (id)initWithDictionary:(NSDictionary*)jsonDic
    {
        if ((self = [super init]))
        {
            [self setValuesForKeysWithDictionary:jsonDic];
        }
        return self;
    }
    
    - (void)setValue:(id)value forKey:(NSString *)key
    {
        [super setValue:value forKey:key];
    }
    
    - (void)setValue:(id)value forUndefinedKey:(NSString *)key
    {
        NSLog(@"Undefined Key:%@ in %@",key,[self class]);
    }
    
    #pragma mark 数据持久化
    - (void)encodeWithCoder:(NSCoder *)aCoder
    {
        unsigned int outCount, i;
        objc_property_t *properties =class_copyPropertyList([self class], &outCount);
        
        for (i = 0; i < outCount; i++)
        {
            objc_property_t property = properties[i];
            const char* char_f = property_getName(property);
            NSString *propertyName = [NSString stringWithUTF8String:char_f];
            id propertyValue = [self valueForKey:(NSString *)propertyName];
            
            if (propertyValue)
            {
                [aCoder encodeObject:propertyValue forKey:propertyName];
            }
        }
    }
    
    - (id)initWithCoder:(NSCoder *)aCoder
    {
        self = [super init];
        if (self)
        {
            unsigned int outCount, i;
            objc_property_t *properties =class_copyPropertyList([self class], &outCount);
            
            for (i = 0; i<outCount; i++)
            {
                objc_property_t property = properties[i];
                const char* char_f = property_getName(property);
                NSString *propertyName = [NSString stringWithUTF8String:char_f];
                
                NSString *capital = [[propertyName substringToIndex:1] uppercaseString];
                NSString *setterSelStr = [NSString stringWithFormat:@"set%@%@:",capital,[propertyName substringFromIndex:1]];
                
                SEL sel = NSSelectorFromString(setterSelStr);
                
                [self performSelectorOnMainThread:sel
                                       withObject:[aCoder decodeObjectForKey:propertyName]
                                    waitUntilDone:[NSThread isMainThread]];
            }
        }
        return self;
    }
    

    比如说我们有个用户类UserModel继承了BaseModel

    UserModel.h

    #import "BaseModel.h"
    
    @interface UserModel : BaseModel
    
    @property (nonatomic , copy) NSString *user_name;
    
    @property (nonatomic , copy) NSString *user_image;
    
    @end
    

    UserModel.m

    #import "UserModel.h"
    
    @implementation UserModel
    -(void)setValue:(id)value forKey:(NSString *)key
    {
        [super setValue:[NSString stringWithFormat:@"%@",value] forKey:key];
    }
    
    @end
    

    在控制器中使用模型接收数据

    [self.manager POST:@"此处填上相应的接口" parameters:params progress:^(NSProgress * _Nonnull uploadProgress)//params是接口的参数字典
    {
             
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
    {
         NSDictionary *dic = responseObject[@"data"]//比如说返回的数据中data是我们要接受的数据
             
         UserModel *model = [[UserModel alloc] initWithDictionary:dic];//此处接收数据   
    
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
    {
         NSLog(@"%@--",error);
    }];
    

    这样我们就获得了数据,可以用它来对控件赋值,也可以+ (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path;来归档数据,而不用在遵守NSCoding,写相应的方法了。是不是很简单了呢?


    注:相关内容我会继续更新。如果想找一些iOS方面的代码可以关注我的简书,我会持续更新,大家一起探讨探讨
    在此谢谢大家阅读

    相关文章

      网友评论

      • 南华coder:initWithCoder中最好使用[self setValue:propertyValue forKeyPath: propertyName];你用performSelectorOnMainThread不能设置非对象(BOOL等)的属性吧
      • terwergreen:kvc这样会有问题,如果服务器返回的字段与模型不一致会崩溃,yymodel这类框架对这个处理的很好。
        帅只是表象:@忆梦Coder - (void)setValue:(id)value forUndefinedKey:(NSString *)key这个方法能过滤掉不存在的键值,不会崩溃。
      • UItachi:KVC不是这么玩的; 关于所谓的数据持久化,这个想法跟http://www.jianshu.com/p/bd24c3f3cd0a 这篇文章一样烂
        小码僧:链接失效了,你可以指的更具体吗

      本文标题:iOS 数据模型基类

      本文链接:https://www.haomeiwen.com/subject/wrjxrttx.html