0

i know its stupid but how do i recreate this array to a plist list

    candyArray = [NSArray arrayWithObjects:
              [Candy candyOfCategory:@"chocolate" name:@"chocolate bar"],
              [Candy candyOfCategory:@"chocolate" name:@"chocolate chip"],
              [Candy candyOfCategory:@"chocolate" name:@"dark chocolate"],
              [Candy candyOfCategory:@"hard" name:@"lollipop"],
              [Candy candyOfCategory:@"hard" name:@"candy cane"],
              [Candy candyOfCategory:@"hard" name:@"jaw breaker"],
              [Candy candyOfCategory:@"other" name:@"caramel"],
              [Candy candyOfCategory:@"other" name:@"sour chew"],
              [Candy candyOfCategory:@"other" name:@"peanut butter cup"],
              [Candy candyOfCategory:@"other" name:@"gummi bear"], nil];

thanks for anyones help!

Andy Howard
  • 41
  • 1
  • 6

2 Answers2

0

Try like this but before that include your array and then follow below:-

NSFileManager *fileManager =[NSFileManager defaultManager];
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask,YES);
        NSString *desktopDirectory = [paths objectAtIndex:0];
          NSString *path = [desktopDirectory stringByAppendingPathComponent:@"yourfile.plist"];
         NSMutableDictionary *mut=[NSMutableDictionary dictionary];

     [mut setObject:candyArray forKey:@"yourKey"];
      If ([mut writeToFile:path automatically:YES])
       {
       NSLog(@"file created");
        }
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56
0

Andy,

Hussain's answer is close but will fail when archiving the custom type.

Simple answer. You must adopt the NSCoding protocol since your using a custom class (Candy). Implement the following tasks initWithCoder, encodeWithCoder and the default archiver will take care of the rest. If you would like to archive in other formats (Binary etc) please reference NSData and NSCoder (NSKeyedArchiver). JSON is also another good lean option.

If this is too much trouble forgo custom objects and nest primitives in arrays or dictionaries. This is discouraged for complex custom types and will build technical debt but encouraged for simple structures. Wanted to share Apple best practices.

Supported plist types (iOS)

NSString, NSNumber, NSDate, NSData, NSArray, NSDictionary

Simple Example (NSArray, NSDictionary) https://developer.apple.com/library/mac/documentation/cocoa/Conceptual/Archiving/Articles/serializing.html#//apple_ref/doc/uid/20000952-BABBEJEE

Full Reference Doc for Custom Objects (NSCoding) https://developer.apple.com/library/mac/documentation/cocoa/Conceptual/Archiving/Archiving.html#//apple_ref/doc/uid/10000047i

Justin Fischer
  • 163
  • 2
  • 8