1

Is it possible to limit an integer in the NSUserDefaults? Off course you can limit it within your app but I am thinking of the TextFields in Settings.

Would be great to get some hints.

Thanks a lot.

danielreiser
  • 5,292
  • 5
  • 31
  • 43
  • What do you mean by "limit an integer"? Do you mean restrict its size so it doesn't display to many characters when rendered as a string? Are you using a settings bundle? – TechZen Mar 27 '10 at 14:36
  • I mean to set a minumum and maximum eg. the minimum is 10 and the max. is 20. – danielreiser Mar 27 '10 at 19:45

1 Answers1

0

I wrote a small VRAppSettings superclass covering that case.

It allows to store your app settings via properties of an object, then archive that object to user defaults automatically.

Here how it can be done. Make a successor of the VRAppSettings class:

@interface MySettings : VRAppSettings
@property (nonatomic, readwrite) NSInteger * myInt;
@end

@implementation MySettings
- (NSString *)userDefaultsKeyPostfix
{
    return @"MyAppsSettings";
}
- (void)resetToDeveloperDefaults
{ 
    // Set default values here
    self.myInt = 85;
}
- (void)checkAfterInitWithCoder { }

- setMyInt(NSString * myInt)
{
    NSInteger max = 110;
    NSInteger min = 80;

    if (myInt > max) myInt = max;
    if (myInt < min) myInt = min;
    _myInt = myInt;
}
@end

Then MySettings can be used as singleton, here how:

[MySettings sharedInstance].myInt = 99;
[[MySettings sharedInstance] synchronizeToUserDefaults];

NSLog(@"myInt = %d", [MySettings sharedInstance].myInt);

In the code above values passed to myInt will be checked in the - setMyInt setter and always be between 80 and 110. MySettings singleton will be stored in user defaults.

See also my blog record for more details.

IvanRublev
  • 784
  • 9
  • 10