Objective-C: PList manager for easy read/write plist files

PlistManager.h

//
//  PlistManager.h
//  Azi
//
//  Created by Cristian Ionescu on 26/02/14.
//  Copyright (c) 2014 Cristian Ionescu. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface PlistManager : NSObject

+(NSString *)getPathToPlistForResorce:(NSString *)resource;
+(NSMutableDictionary *)getDictionaryFromPath:(NSString *)pathToPlist;
+(BOOL)writeDictionary:(NSDictionary *)dictionary toPath:(NSString *)pathToPlist;
+(BOOL)updateSettingForKey:(NSString *)key withValue:(NSString *)value;
+(BOOL)doesFileExistAtPath:(NSString *)pathToPlist;
+(NSString *)getSettingValueForKey:(NSString *)key;

@end

PlistManager.m

//
//  PlistManager.m
//  Azi
//
//  Created by Cristian Ionescu on 26/02/14.
//  Copyright (c) 2014 Cristian Ionescu. All rights reserved.
//

#import "PlistManager.h"

@implementation PlistManager

+(NSString *)getPathToPlistForResorce:(NSString *)resource
{
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *settingsPlistPath = [[[bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"];

    return [settingsPlistPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", resource]];
}

+(NSDictionary *)getDictionaryFromPath:(NSString *)pathToPlist
{
    return [NSDictionary dictionaryWithContentsOfFile:pathToPlist];
}

+(BOOL)writeDictionary:(NSDictionary *)dictionary toPath:(NSString *)pathToPlist
{
    return [dictionary writeToFile:pathToPlist atomically:YES];
}

+(BOOL)updateSettingForKey:(NSString *)key withValue:(NSString *)value
{
    NSString *settingsDictionaryPlistPath = [PlistManager getPathToPlistForResorce:@"Settings"];
    if ([PlistManager doesFileExistAtPath:settingsDictionaryPlistPath])
    {
        NSMutableDictionary *settingsDictionary = [PlistManager getDictionaryFromPath:settingsDictionaryPlistPath];
        [settingsDictionary setValue:value forKey:key];
        return [settingsDictionary writeToFile:settingsDictionaryPlistPath atomically:YES];
    }
    else
    {
        NSMutableDictionary *settingsDictionary = [NSMutableDictionary new];
        [settingsDictionary setValue:value forKey:key];
        return [settingsDictionary writeToFile:settingsDictionaryPlistPath atomically:YES];
    }
}

+(NSString *)getSettingValueForKey:(NSString *)key
{
    NSDictionary *settingsDictionary = [PlistManager getDictionaryFromPath:[PlistManager getPathToPlistForResorce:@"Settings"]];
    return [settingsDictionary valueForKey:key];
}

+(BOOL)doesFileExistAtPath:(NSString *)pathToPlist
{
    NSFileManager *fileManager = [NSFileManager new];
    return [fileManager fileExistsAtPath:pathToPlist];
}


@end

Leave a Reply