iOS 數據模型基類

在項目中,我們常常會用到數據模型,我們會用它來接收數據或者保存數據。你有沒有覺的每次使用的時候都很麻煩呢,要寫很多代碼?不要緊,我們可以寫一個數據模型的基礎類,每次創建的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方面的代碼可以關注我的簡書,我會持續更新,大家一起探討探討
在此謝謝大家閱讀

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容