archive存取

来源:互联网 发布:网络诈骗报警平台登录 编辑:程序博客网 时间:2024/05/23 02:06

必须在Model类里遵守NSCoding协议,并实现两个必须实现的方法

//遵守NSCoding协议并实现两个必须实现的方法- (void)encodeWithCoder:(NSCoder *)aCoder;- (id)initWithCoder:(NSCoder *)aDecoder;

具体实现:

- (void)encodeWithCoder:(NSCoder *)aCoder{    [aCoder encodeObject:self.yourName forKey:@"yourName"];}- (id)initWithCoder:(NSCoder *)aDecoder{    self = [super init];    if (self) {        [aDecoder decodeObjectForKey:@"yourName"];    }    return self;}

ArchiveStore.h

#import <Foundation/Foundation.h>@interface MDRArchiveStore : NSObject{    NSMutableArray *allItems;}// 单例方法+ (MDRArchiveStore *)sharedStore;+ (id)allocWithZone:(struct _NSZone *)zone;- (id)init;@end

ArchiveStore.m

+ (MDRArchiveStore *)sharedStore{    static MDRArchiveStore *sharedStore = nil;    if (!sharedStore) {        sharedStore = [[super allocWithZone:nil] init];    }    return sharedStore;}+ (id)allocWithZone:(struct _NSZone *)zone{    return [self sharedStore];}- (id)init{    self = [super init];    if (self) {                NSString *path = [self archivePath];        allItems = [NSKeyedUnarchiver unarchiveObjectWithFile:path];        if (!allItems) {            allItems = [[NSMutableArray alloc] init];        }    }    return self;}

固化

#import "MDRArchiveStore.h"@implementation MDRArchiveStore#pragma mark - The single instance method+ (MDRArchiveStore *)sharedStore{    static MDRArchiveStore *sharedStore = nil;    if (!sharedStore) {        sharedStore = [[super allocWithZone:nil] init];    }    return sharedStore;}+ (id)allocWithZone:(struct _NSZone *)zone{    return [self sharedStore];}- (id)init{    self = [super init];    if (self) {                NSString *path = [self archivePath];        allItems = [NSKeyedUnarchiver unarchiveObjectWithFile:path];        if (!allItems) {            allItems = [[NSMutableArray alloc] init];        }    }    return self;}#pragma mark - The archive method- (NSString *)archivePath{    NSArray *documentDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);    NSString *documentDirectories = [documentDirectory objectAtIndex:0];    return [documentDirectories stringByAppendingPathComponent:@"items.archive"];}- (BOOL)savePath{    NSString *path = [self archivePath];    return [NSKeyedArchiver archiveRootObject:allItems toFile:path];}@end







0 0
原创粉丝点击