title: IOS: Save Array when app is close or enter background
body: <p>I have a cartArray(in AppDelegate.h @interface above) that need to be saved when the app in background mode or the app closed. The app worked fine when the cartArray has nothing but crashed when I added an item (Cart) in it and entered the background  or closed the application by pressing the minus sign. My cartArray contains cart class in it.
  May I know what is happening? The tutorial online is so complicated and I always find myself lost in the middle of explanation.</p>
  
  <p>[AppDelegate.m]</p>
  
  <pre><code>- (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]];
  }
  </code></pre>