summaryrefslogtreecommitdiff
path: root/SmartDeviceLink-iOS/SmartDeviceLink_Example/Classes/Preferences.m
blob: f103998da1c5829436f5b7c63dc7d060341e1b95 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
//
//  Preferences.m
//  SmartDeviceLink-iOS

#import "Preferences.h"


NSString *const IPAddressPreferencesKey = @"SDLExampleAppIPAddress";
NSString *const PortPreferencesKey = @"SDLExampleAppPort";

NSString *const DefaultIPAddressValue = @"192.168.1.1";
NSString *const DefaultPortValue = @"12345";



@interface Preferences ()

@end



@implementation Preferences


#pragma mark - Singleton / Initializers

+ (instancetype)sharedPreferences {
    static Preferences *sharedPreferences = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedPreferences = [[Preferences alloc] init];
    });
    
    return sharedPreferences;
}

- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    if (self.ipAddress == nil || self.port == nil) {
        [self resetPreferences];
    }
    
    return self;
}


#pragma mark - Public API

- (void)resetPreferences {
    self.ipAddress = DefaultIPAddressValue;
    self.port = DefaultPortValue;
}


#pragma mark - Setters / Getters

- (NSString *)ipAddress {
    return [self stringForKey:IPAddressPreferencesKey];
}

- (void)setIpAddress:(NSString *)ipAddress {
    [self setString:ipAddress forKey:IPAddressPreferencesKey];
}

- (NSString *)port {
    return [self stringForKey:PortPreferencesKey];
}

- (void)setPort:(NSString *)port {
    [self setString:port forKey:PortPreferencesKey];
}


#pragma mark - Private User Defaults Helpers

- (void)setString:(NSString *)aString forKey:(NSString *)aKey {
    NSParameterAssert(aKey != nil);
    
    dispatch_async(self.class.preferencesQueue, ^{
        [[NSUserDefaults standardUserDefaults] setObject:aString forKey:aKey];
    });
}

- (NSString *)stringForKey:(NSString *)aKey {
    NSParameterAssert(aKey != nil);
    
    __block NSString *retVal = nil;
    dispatch_sync(self.class.preferencesQueue, ^{
        retVal = [[NSUserDefaults standardUserDefaults] stringForKey:aKey];
    });
    
    return retVal;
}


#pragma mark - Class Queue

+ (dispatch_queue_t)preferencesQueue {
    static dispatch_queue_t preferencesQueue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        preferencesQueue = dispatch_queue_create("com.sdl-example.preferences", DISPATCH_QUEUE_SERIAL);
    });
    
    return preferencesQueue;
}

@end