Created
November 6, 2013 17:19
-
-
Save ykst/7340289 to your computer and use it in GitHub Desktop.
単純なオブジェクトを永続化するカテゴリ ref: http://qiita.com/ykst@github/items/c5dcc71efd22e799dc31
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface NSObject(SimpleArchiver) | |
// example: | |
// (archive) | |
// [SomeClass simpleArchiveForKey:@"a_key"]; | |
// (unarchive) | |
// SomeClass *a_obj = [SomeClass simpleUnarchiveForKey:@"a_key"]; | |
- (BOOL)simpleArchiveForKey:(NSString *)key; | |
+ (id)simpleUnarchiveForKey:(NSString *)key; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "NSObject+SimpleArchiver.h" | |
#import <objc/runtime.h> | |
#define NSPRINTF(fmt, ...) [NSString stringWithFormat:fmt, ##__VA_ARGS__] | |
@implementation NSObject(SimpleArchiver) | |
+ (NSString *)_makeArchivePath:(Class)cls forKey:(NSString *)key | |
{ | |
// 保存場所はアプリケーションにより要調整 | |
NSString *plain = NSPRINTF(@"_SA_%@_%@", NSStringFromClass(cls), key); | |
NSArray *document_paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, | |
NSUserDomainMask, YES); | |
NSString *documents_path = [document_paths objectAtIndex:0]; | |
NSString *path = NSPRINTF(@"%@/%@", documents_path, plain); | |
return path; | |
} | |
- (BOOL)simpleArchiveForKey:(NSString *)key | |
{ | |
NSString *archive_key = [NSObject _makeArchivePath:[self class] forKey:key]; | |
unsigned count; | |
objc_property_t *properties = class_copyPropertyList([self class], &count); | |
if (count == 0) return NO; | |
NSMutableArray *keys = [NSMutableArray arrayWithCapacity:count]; | |
for (int i = 0; i < count; ++i) { | |
objc_property_t property = properties[i]; | |
keys[i] = [NSString stringWithUTF8String:property_getName(property)]; | |
} | |
NSDictionary *dict = [self dictionaryWithValuesForKeys:keys]; | |
BOOL ret = [NSKeyedArchiver archiveRootObject:dict toFile:archive_key]; | |
return ret; | |
} | |
+ (id)simpleUnarchiveForKey:(NSString *)key | |
{ | |
NSString *archive_key = [NSObject _makeArchivePath:[self class] forKey:key]; | |
NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithFile:archive_key]; | |
if (!dict) return nil; | |
NSObject *obj = [[self class] new]; | |
[obj setValuesForKeysWithDictionary:dict]; | |
return obj; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment