10 September 2011

Wrappers in Objective-c

  1. //string_2_primtiives.m
  2. #import <Foundation/Foundation.h>
  3. 
  4. /**
  5. *    You can convert the following to each other
  6. *    NSNumber <=> primitives <=> NSString 
  7. */
  8. 
  9. int main(void)
 10. {
 11.     NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
 12. 
 13.     //1- primitives => NSNumber
 14.     NSNumber* intNum = [NSNumber numberWithInteger: 20];
 15.     NSNumber* floatNum = [NSNumber numberWithFloat: 25.325];
 16.     
 17.     NSLog(@"%@ %@", intNum, floatNum);
 18.     
 19.     // 2- NSNumber => primitives:
 20.     int x = [intNum intValue];
 21.     float f = [floatNum floatValue];
 22.     // also, we can convert nay number object (regards of which value it contains) to any primitives type
 23.     //, and the standard C casting rules will be applied:
 24.     int x2 = [floatNum intValue];
 25.     
 26.     NSLog(@"%d %g %d", x, f, x2);
 27.     
 28.     // 3- primitives => NSString:
 29.     NSString* string = [NSString stringWithFormat: @"%d",x];
 30.     NSLog(@"%@", string);
 31.     
 32.     // 4- NSString = > primitives:
 33.     int i = [@"1" intValue];
 34.     float g = [@"13.4" floatValue];
 35.     int i2 = [@"13.4" intValue];
 36.     
 37.     NSLog(@"%d %g %d", i, g, i2);
 38.     
 39.     // 5- NSNumber => NSString
 40.     NSString* str = [NSString stringWithFormat:@"%@", [NSNumber numberWithBool:20]];
 41.     NSLog(@"%@", str);
 42.     
 43.     // 6- NSString => NSNumber 
 44.     NSNumber* charNum = [NSNumber numberWithChar: [@"20" intValue]];
 45.     NSLog(@"%@", charNum);
 46.     
 47.     [pool release];
 48.     return 0;
 49. }
 50. 
 51. /** output:
 52. 
 53. 20 25.325
 54. 20 25.325 25
 55. 20
 56. 1 13.4 13
 57. 1
 58. 20
 59. 
 60. */
Post a Comment