FastCoder 之单例的本地存储高度封装优化

修改时间: 2016-12-05

修改次数: 0


需要设置:手动管理(-fno-objc-arc)

项目->Build Phases-> Compile Sources

下面类似的图

QQ20161205-0.jpg

gitHub : FastCoding

FastCoding 减少了对自定义类时的协议书写


接下来是用单例模式来本地存储数据



@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"; //这是严格的单例模式书写

        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); //如果为空,将会报错。

    NSParameterAssert(key);

    NSData *data= [FastCoder dataWithRootObject:value];//FastCoder 的内容

    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"]);


高度封装:

书写时,发现每次都要使用Center shar.....很长。


@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"];

你可能感兴趣的:(FastCoder 之单例的本地存储高度封装优化)