Saving to a .plist file in Objective-C

Here’s a basic how-to for saving data to a .plist file. 

1. Set up helper methods for getting the directory

- (NSURL *)documentsDirectory {
    NSArray *paths = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
    
    return paths[0];
}

- (NSURL *)dataFilePath {
    return [[self documentsDirectory] URLByAppendingPathComponent:@"Checklists.plist"];
}

2. Implement a saving method in your controller

- (void)saveChecklistItems {
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    
    [archiver encodeObject:items forKey:@"ChecklistItems"];
    [archiver finishEncoding];
    [data writeToURL:[self dataFilePath] atomically:YES];
}

3. Call the method in appropriate places (such as delegate methods)

4. Declare that the object being saved will conform to the NSCoding protocol in the header file

@interface ChecklistItem : NSObject <NSCoding>

5. Implement the methods for the NSCoding protocol in the model for the object you are saving (in this example, ChecklistItem.m)

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self.text = [aDecoder decodeObjectForKey:@"Text"];
    self.checked = [aDecoder decodeBoolForKey:@"Checked"];
    
    self = [super init];
    
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.text forKey:@"Text"];
    [aCoder encodeObject:[NSNumber numberWithBool:self.checked] forKey:@"Checked"];
}

6. Retrieve the items from the file to the view controller (in this example, ChecklistViewController.m)

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    items = [NSMutableArray array];
    
    self = [super initWithCoder:aDecoder];
    
    [self loadChecklistItems];
    
    return self;
}

- (void)loadChecklistItems {
    NSData *data = [[NSData alloc] initWithContentsOfURL:[self dataFilePath]];
    
    if (data) {
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        
        items = [unarchiver decodeObjectForKey:@"ChecklistItems"];
        
        [unarchiver finishDecoding];
    }
}

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.