.h
#import <Foundation/Foundation.h> @interface LocalData : NSObject + (instancetype)read:(NSString *)name; + (void)save:(NSString *)name className:(id)className; @end
.m
#import "LocalData.h" @implementation LocalData + (instancetype)read:(NSString *)name { // NSData *_data = [[NSData alloc] initWithContentsOfFile:[self getFilePathWithModelKey:name]]; // //解档辅助类 // NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:_data]; // //解档出数据模型Student // //解码并解档出model // id model = [unarchiver decodeObjectForKey:name]; // //关闭解档 // [unarchiver finishDecoding]; // return model; //获得保存数据 NSData *getthemeAndAboutData = [[NSUserDefaults standardUserDefaults] objectForKey:name]; //转成模型获取数据 id model = [NSKeyedUnarchiver unarchiveObjectWithData:getthemeAndAboutData]; return model; //return [NSKeyedUnarchiver unarchiveObjectWithFile:[self getFilePathWithModelKey:name]]; } + (void)save:(NSString *)name className:(id)className { // BOOL success = [NSKeyedArchiver archiveRootObject:className toFile:[self getFilePathWithModelKey:name]]; // NSLog(@"保存的状态%d",success); ///////////////////////归档 // //需要用NSMutableData来中中介 // NSMutableData *data = [[NSMutableData alloc] init]; // //创建归档辅助类 // NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; // //编码 // [archiver encodeObject:className forKey:name]; // //结束编码 // [archiver finishEncoding]; // //写入 // [data writeToFile:[self getFilePathWithModelKey:name] atomically:YES]; NSData *themeAndAboutData = [NSKeyedArchiver archivedDataWithRootObject:className]; [[NSUserDefaults standardUserDefaults] setObject:themeAndAboutData forKey:name]; [[NSUserDefaults standardUserDefaults] synchronize]; } //得到目录 +(NSString *) getFilePathWithModelKey:(NSString *)modelkey { NSArray *array = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); return [[array objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.archiver",modelkey]]; } @end
时间: 2024-11-13 09:58:53