Skip to content

Instantly share code, notes, and snippets.

@hollance
Created August 24, 2013 13:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hollance/6328192 to your computer and use it in GitHub Desktop.
Save hollance/6328192 to your computer and use it in GitHub Desktop.
Saving an NSMutableArray to a plist file using NSKeyedArchiver and NSCoding.
// Gets the path to the app's Documents folder
- (NSString *)documentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return paths[0];
}
// Gets the path to the data file
- (NSString *)dataFilePath
{
return [[self documentsDirectory] stringByAppendingPathComponent:@"YOUR-FILENAME-HERE.plist"];
}
// Loads the array from the file or creates a new array if no file present
- (NSMutableArray *)loadArray
{
NSMutableArray *array;
NSString *path = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
array = [unarchiver decodeObjectForKey:@"MY_ARRAY"];
[unarchiver finishDecoding];
} else {
array = [[NSMutableArray alloc] initWithCapacity:20];
}
return array;
}
// Saves the array to a file
- (void)saveArray:(NSMutableArray *)array
{
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:array forKey:@"MY_ARRAY"];
[archiver finishEncoding];
[data writeToFile:[self dataFilePath] atomically:YES];
}
// Make the object conform to the NSCoding protocol
@interface YourObject : NSObject <NSCoding>
@property (nonatomic, copy) NSString *name;
// and other properties here...
@end
#import "YourObject.h"
@implementation YourObject
- (id)init
{
if ((self = [super init])) {
self.name = @"Some default name";
// initialize any other properties here
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if ((self = [super init])) {
self.name = [aDecoder decodeObjectForKey:@"Name"];
// decode any other properties here
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"Name"];
// encode any other properties here
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment