iOS 數(shù)據(jù)模型基類

在項目中,我們常常會用到數(shù)據(jù)模型,我們會用它來接收數(shù)據(jù)或者保存數(shù)據(jù)。你有沒有覺的每次使用的時候都很麻煩呢,要寫很多代碼?不要緊,我們可以寫一個數(shù)據(jù)模型的基礎類,每次創(chuàng)建的model類繼承它就可以方便使用了,是不是很簡單呢!

BaseModel.h

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface BaseModel : NSObject

//接收數(shù)據(jù)使用
- (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 數(shù)據(jù)持久化
- (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

在控制器中使用模型接收數(shù)據(jù)

[self.manager POST:@"此處填上相應的接口" parameters:params progress:^(NSProgress * _Nonnull uploadProgress)//params是接口的參數(shù)字典
{
         
} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
{
     NSDictionary *dic = responseObject[@"data"]//比如說返回的數(shù)據(jù)中data是我們要接受的數(shù)據(jù)
         
     UserModel *model = [[UserModel alloc] initWithDictionary:dic];//此處接收數(shù)據(jù)   

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
{
     NSLog(@"%@--",error);
}];

這樣我們就獲得了數(shù)據(jù),可以用它來對控件賦值,也可以+ (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path;來歸檔數(shù)據(jù),而不用在遵守NSCoding,寫相應的方法了。是不是很簡單了呢?


注:相關內(nèi)容我會繼續(xù)更新。如果想找一些iOS方面的代碼可以關注我的簡書,我會持續(xù)更新,大家一起探討探討
在此謝謝大家閱讀

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容