IOS:当应用关闭或进入后台时保存数组

sho*_*_sm 5 iphone objective-c save ios

我有一个cartArray(在AppDelegate.h @interface上面),当应用程序在后台模式或应用程序关闭时需要保存.当cartArray在我添加一个项目(Cart)并输入背景或按下减号关闭应用程序时,该应用程序工作正常.我的cartArray中包含了cart类.我可以知道发生了什么吗?在线教程非常复杂,我总是发现自己迷失在解释的中间.

[AppDelegate.m]

- (void)applicationDidEnterBackground:(UIApplication *)application {
[AppDelegate saveData]; 
}

- (void)applicationWillEnterForeground:(UIApplication *)application {   
[AppDelegate getData];   
}

+(NSString *) getPathToAchieve{  NSLog(@"+++++getPathToAchieve");
    static NSString* docsDir = nil;
    if (docsDir == nil) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        docsDir = [paths objectAtIndex:0];
    }
    NSString *fullFileName = [NSString stringWithFormat:@"%@.plist", docsDir];
    return fullFileName;
}

- (void)applicationWillTerminate:(NSNotification *)notification{    
    [cartArray writeToFile:[AppDelegate getPathToAchieve] atomically:YES];
}

-(id)initWithCoder:(NSCoder *)aDecoder
{   self = [super init];
   if (self != nil)
   {
        cartArray = [aDecoder decodeObjectForKey:@"cartArrayKeys"];
   }
    return self;  
}

-(void)encodeWithCoder:(NSCoder *)anEncoder
{   
    [anEncoder encodeObject:cartArray forKey:@"cartArrayKeys"];
}

+(void)saveData{ 
     [NSKeyedArchiver archiveRootObject:cartArray toFile:[self getPathToAchieve] ];
}

+(id)getData{ 
    return [NSKeyedUnarchiver unarchiveObjectWithFile:[self getPathToAchieve]];
}
Run Code Online (Sandbox Code Playgroud)

And*_*eev 1

你的代码相当混乱。首先,在你的类中实现-(id)initWithCoder:and ,而不是类(并确保符合协议):-(void)encodeWithCoder:CartAppDelegateCartNSCoding

- (void) encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:self.title forKey:@"title"];
    [encoder encodeObject:self.description forKey:@"description"];
    .....
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.title = [decoder decodeObjectForKey:@"title"] ;
        self.description = [decoder decodeObjectForKey:@"description"] ;
        ....
    }
    return self;
}   
Run Code Online (Sandbox Code Playgroud)

其次,实施-(void)saveData-(void)getData

-(void)saveData{ 
     [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:cartArray] forKey:@"cartArray"];
}

-(void)getData{ 
    NSData *savedArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"cartArray"];
    if (savedArray != nil)
    {
        NSArray *oldArray = [NSKeyedUnarchiver unarchiveObjectWithData:savedArray];
        if (oldArray != nil) {
            cartArray = [[NSMutableArray alloc] initWithArray:oldArray];
        } else {
            cartArray = [[NSMutableArray alloc] init];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

saveData当应用程序将要终止/进入后台时调用。getData应用程序加载后调用。