首页 > 代码库 > 让NSUserDefaults使用起来像对象一样容易

让NSUserDefaults使用起来像对象一样容易

让NSUserDefaults使用起来像对象一样容易

巧妙的设计,是为了简化开发提升效率而存在。

 

设计要点:

1. 单例模式

2. 重写setter,getter方法

3. 专门的类来管理单例

 

使用时候的详情:

源码:

SharedInstance.h 与 SharedInstance.m

////  SharedInstance.h//  NSUserDefault////  Created by YouXianMing on 14/12/5.//  Copyright (c) 2014年 YouXianMing. All rights reserved.//#import <Foundation/Foundation.h>#import "NSUserDefaultsObject.h"/** *  单例管理器 */@interface SharedInstance : NSObject+ (NSUserDefaultsObject *)defaultsObject;@end
////  SharedInstance.m//  NSUserDefault////  Created by YouXianMing on 14/12/5.//  Copyright (c) 2014年 YouXianMing. All rights reserved.//#import "SharedInstance.h"static NSUserDefaultsObject *_defaultObject = nil;@implementation SharedInstance/** *  构造单例的类方法 */+ (void)initialize {    if (self == [SharedInstance class]) {        _defaultObject = [NSUserDefaultsObject new];    }}+ (NSUserDefaultsObject *)defaultsObject {    return _defaultObject;}@end

NSUserDefaultsObject.h 与 NSUserDefaultsObject.m

////  NSUserDefaultsObject.h//  NSUserDefault////  Created by YouXianMing on 14/12/5.//  Copyright (c) 2014年 YouXianMing. All rights reserved.//#import <Foundation/Foundation.h>@interface NSUserDefaultsObject : NSObject@property (nonatomic, strong) NSString  *name;@end
////  NSUserDefaultsObject.m//  NSUserDefault////  Created by YouXianMing on 14/12/5.//  Copyright (c) 2014年 YouXianMing. All rights reserved.//#import "NSUserDefaultsObject.h"@implementation NSUserDefaultsObject#pragma mark - 重写setter,getter方法@synthesize name = _name;- (void)setName:(NSString *)name {    [[NSUserDefaults standardUserDefaults] setValue:name forKey:@"name"];}- (NSString *)name {    return [[NSUserDefaults standardUserDefaults] valueForKey:@"name"];}@end

核心源码:

 

让NSUserDefaults使用起来像对象一样容易