- FastCoder,能够帮你存储你建立的模型和基本数据类型,它是
NSUserDefaults
的进一步封装。- FastCoding 减少了对自定义类时的
<NScoding>
协议书写
需要设置:手动管理(-fno-objc-arc)
项目->Build Phases-> Compile Sources
下面类似的图
接下来是用单例模式来本地存储数据
@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"]);
进一步的封装:
@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"];