Work With Numbers in Objective C (NSNumber and NSDigitalNumber)
Next example shows you how to work with NSNumber and NSDecimalNumer objects in Objective C. First part show you standard use, second part shows how to work with NSNumer objects in simplified form and last part shows how to work with NSDecimalNumber objects.
In this example we define two NSNumber numbers and then we add them (or we muliply them).
NSNumber *a, *b, *c; a = [NSNumber numberWithInt:10]; b = [NSNumber numberWithInt:20]; c = [NSNumber numberWithInt:([a intValue] + [b intValue])]; // short notations a = @10; b = @20; c = @([a integerValue] * [b integerValue]); // using NSDecimalNumbers NSDecimalNumber *a1, *a2, *a3; a1 = [[NSDecimalNumber alloc] initWithInt:15]; a2 = [[NSDecimalNumber alloc] initWithInt:30]; a3 = [a1 decimalNumberByMultiplyingBy:a2]; // define a boolean number NSNumber *isItTrue = @YES; // convert string to int int val1 = [@"100" intValue]; NSNumber *d = [NSNumber numberWithInt:val1]; NSLog(@"\n isItTrue = %@ | d = %@", isItTrue, d); |
You can also learn how to convert a NSString to a NSNumber object.
Working with NSNumbers to make computations is slow. Better use C type numbers instead. But anyway just in case you need this, it might be useful to know how to use NSNumber object to make mathematical operations.
Renaming a Getter in Objective C When Using @property
If we use @property to define setters and getters for our class variables if we want our getter name to be different (by default if we do not rename it, our getter have the same name as the variable name) we will use the following syntax:
@property (strong, nonatomic, getter=showJustAString) NSString *justAString
That way our getter will be showJustAString.
Note that by default when we define the property using:
@property (strong, nonatomic) NSString *justAString
our getter will be justAString.