我尝试了不同的方法,但无法得到正确的解决方案。 我有一个单例数组,我的HomeVC中保存了键值对数组。此数组将保存在NSUserDefaults中,并在另一个Class RewardsVC中检索。但是一旦应用程序被杀死并重新启动,单例数组中的所有数据都将被删除。对此有何帮助? 这是代码:
if ([json objectForKey:JSON_KEY_REWARDS])
{
if([[json objectForKey:JSON_KEY_REWARDS] objectForKey:JSON_KEY_REWARD_ARRAY]){
NSMutableArray *newRewardArray=[[json objectForKey:JSON_KEY_REWARDS] objectForKey:JSON_KEY_REWARD_ARRAY];
if([newRewardArray count] > 0){
shouldUpdate = TRUE;
}
for (NSMutableDictionary *reward in newRewardArray)
{
NSMutableDictionary *mutableReward = reward ;
[[Utility getSharedInstance].rewardsFuckingArray addObject:mutableReward];
}
}
[[NSUserDefaults standardUserDefaults] setObject:[Utility getSharedInstance].rewardsFuckingArray forKey:@"yourKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
Utility是我的Singleton类,我在Utility.h中做了@property (strong, nonatomic) NSMutableArray *rewardsFuckingArray;
+(Utility*) getSharedInstance;
。
在Utility.m中:
+(Utility*) getSharedInstance
{
static Utility* _shared = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_shared = [[self alloc] init];
});
return _shared;
}
- (id)init {
if (self = [super init]) {
self.rewardsFuckingArray = [[NSMutableArray alloc] init];
}
return self;
}
I RewardsVC.m,我这样做了:
rewardsArray = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"yourKey"] mutableCopy];
答案 0 :(得分:0)
当应用程序被杀死时,您需要从NSUserDefaults
加载数据。您可以在构建单个Utility
实例时执行此操作,方法是在Utility.m文件中实现-(id)init
方法,如下所示:
- (id)init
{
if (self = [super init])
{
NSArray* rewards = [[NSUserDefaults standardUserDefaults] objectForKey:@"yourKey"];
if (rewards != nil)
{
self.rewardsFuckingArray = [NSMutableArray arrayWithArray:rewards];
}
else
{
self.rewardsFuckingArray = [[NSMutableArray alloc] init];
}
}
return self;
}