NSUserDefaults之FastCoder 存儲

  1. FastCoder,能夠幫你存儲你建立的模型和基本數(shù)據(jù)類型,它是NSUserDefaults的進(jìn)一步封裝。
  2. FastCoding 減少了對自定義類時(shí)的<NScoding>協(xié)議書寫

gitHub : FastCoding

需要設(shè)置:手動管理(-fno-objc-arc)

項(xiàng)目->Build Phases-> Compile Sources

下面類似的圖

QQ20161205-0.jpg

接下來是用單例模式來本地存儲數(shù)據(jù)

@interface Center : NSObject

+(instancetype)share;
-(void)storeValue:(id)value withKey:(NSString *)key;
-(id)valueWithKey:(NSString *)key;
#import "Center.h"
#import "FastCoder.h"

static Center *center =nil;

@implementation Center

+(instancetype)share{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        center = (Center *)@"Center"; //這是嚴(yán)格的單例模式書寫
        center = [[Center alloc]init];
    });

    //防止子類使用
    NSString *classString = NSStringFromClass([self class]);
    if ([classString isEqualToString:@"Center"] == NO) {
        NSParameterAssert(nil);
    }
    return center;
}

-(instancetype)init{
    NSString *string = (NSString *)center;
    if ([string isKindOfClass:[NSString class]] && [string isEqualToString:@"Center"]) {
        self = [super init];
        if (self) {}
        return self;
    }else{
        return nil;
    }
}

-(void)storeValue:(id)value withKey:(NSString *)key{
    NSParameterAssert(value); //如果為空,將會報(bào)錯(cuò)。
    NSParameterAssert(key);
    NSData *data= [FastCoder dataWithRootObject:value];//FastCoder 的內(nèi)容
    if (data) {
        [[NSUserDefaults standardUserDefaults]setObject:data forKey:key];
    }
}

-(id)valueWithKey:(NSString *)key{
    NSParameterAssert(key);
    NSData *data = [[NSUserDefaults standardUserDefaults]valueForKey:key];
    return [FastCoder objectWithData:data];
}

使用如下:

 [[Center share]storeValue:@{@"a":@"b"} withKey:@"key"];
 NSLog(@"%@",[[Center share]valueWithKey:@"key"]);

進(jìn)一步的封裝:

@interface NSObject (StoreValue)
-(void)storeValueWithKey:(NSString *)key;
+(id)valueBykey:(NSString *)key;
@end
#import "NSObject+StoreValue.h"
#import "Center.h"
@implementation NSObject (StoreValue)
-(void)storeValueWithKey:(NSString *)key{
    [[Center share]storeValue:self withKey:key];
}

+(id)valueBykey:(NSString *)key{
    return  [[Center share]valueWithKey:key];
}

使用如下:

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

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

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