Monday, September 8, 2014

Creating a custom setter and getter for a property in Objective C


When creating the mobile application Jano I had to show different statistics in a special menu. It had to appear in a label (of course) and I wanted to format it according to the phone's style.

The best solution for me was to add a string property to the model that would return the NSNumber property formatted accordingly.

In the .h file I defined the public properties as follows:


@property (nonatomic, strong) NSString *ValueAsString;

@property (nonatomic, strong) NSNumber *Value;


In the .m file, the code appear like this:
@synthesize Value = _value, ValueAsString = _valueAsString; 


//Getter for ValueAsString
-(NSString*) ValueAsString
{
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setGroupingSeparator:[[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator]];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *result = [formatter stringFromNumber:_value];

    return result;
}

-(void)setValueAsString:(NSString*)value
{
_valueAsString = value;
}
Although I had no use for the setter, I added it here so that it would be a full example.

No comments:

Post a Comment