1、创建一个moder (继承NSObject的类,我们可以在一个类里面写多个moder) 继承<NSCoding>
@interface storageModer : NSObject
@property(nonatomic,strong)NSMutableArray * storage_moder;
@end
2、在moder中实现两个方法
@implementation storageModer
// 告诉需要 需要归档哪些属性
- (void)encodeWithCoder:(NSCoder*)aCoder
{
[aCoder encodeObject:_storage_moder forKey:@"storage"];
}
// 告诉系统解档哪些属性
- (instancetype)initWithCoder:(NSCoder*)aDecoder
{
if (self = [super init]) {
_storage_moder = [aDecoder decodeObjectForKey:@"storage"];
}
return self;
}
@end
//存储路径的宏
#define kFilePath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"storage2.data"]
3、调用存储数据
//读存数据
storageModer * storage_out = [NSKeyedUnarchiver unarchiveObjectWithFile:kFilePath];
storage_out.storage_moder[self.Then_int][Transformation_int+1]=@"1";
storage_out.storage_moder[4][0] =[NSString stringWithFormat:@"%d",[storage_out.storage_moder[4][0] intValue]+pass_Coin] ;
//存储数据
storageModer * storage_in = [[storageModer alloc]init];
storage_in.storage_moder = storage_out.storage_moder;
[NSKeyedArchiver archiveRootObject:storage_in toFile:kFilePath];
4、App首次启动时初始化数据
//判断app是否首次启动
- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(nullable NSDictionary *)launchOptions{
NSArray * name = [[NSArray alloc]initWithObjects:@"Sium",@"Tom",@"YonG",@"QuAn",@"Greent", nil];
if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"]){
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"];
NSLog(@"第一次启动");
//获取路径
storageModer * storage = [[storageModer alloc]init];
NSString * name_str =name[arc4random()%4];
NSMutableArray * one_check = [NSMutableArray arrayWithObjects:@"1",@"0",@"0",@"0", nil];
NSMutableArray * two_check = [NSMutableArray arrayWithObjects:@"1",@"0",@"0",@"0", nil];
NSMutableArray * three_check = [NSMutableArray arrayWithObjects:@"1",@"0",@"0",@"0", nil];
NSMutableArray * four_check = [NSMutableArray arrayWithObjects:@"1",@"0",@"0",@"0", nil];
NSMutableArray * five = [NSMutableArray arrayWithObjects:@"0",name_str, nil];
storage.storage_moder = [NSMutableArray arrayWithObjects:one_check,two_check,three_check ,four_check,five, nil];
[NSKeyedArchiver archiveRootObject:storage toFile:kFilePath];
}
return YES;
}
数据每次存储需要全部将数据全部赋值,没赋值的就清零。所以以建NSMutableArray或字典最佳