The type casting in Objective C.
I have id declared value. And I need it to convert into float value. How can I make it. I tried the type casting bur it did not work. I need to store the values in my NSArray in an two dimensional array. My two dimensional array is stores float values in it. Can I do this? Did I am totally in wrong thinking ? Can any one please help me ?
I'd like to explain the difference between Obj/C object and 'Straight C' (and I hope this is helpful and not patronizing).
Obj/C. An id is a pointer to any object (and NSObject*). So an id could be an NSString* or an NSNumber* or any object really. An NSArray can hold any number of id's. The methods of an object have names (signatures) which usually convey their meaning. So [id integerValue] will the recover the 'C' int value of an object. For an NSNumber* , this is quite simple, for an NSString* this will involve decoding the string. The thing to notice is that you have to use the methods to operate on a Obj/C object.
C. An array in C is a block of memory and you have double array[10] would hold 10 doubles. You can't cast an Obj/C object to a C double* and expect to get anything very useful (as I show in a moment).
I've written a simple command line program:
NSString* nsString = @"12345" ;
NSNumber* nsNumber = [[NSNumber alloc] initWithInt:911] ;
id idString = nsString ;
id idNumber = nsNumber ;
NSMutableArray* array = [[NSMutableArray alloc]init] ;
[array addObject:nsString] ;
[array addObject:nsNumber] ;
[array addObject:idString] ;
[array addObject:idNumber] ;
NSUInteger i ;
for ( i = 0 ; i < [array count] ; i++ )
NSLog(@"i = %d item = %@",i,[array objectAtIndex:i]);
i = 0 ; NSLog(@"i = %d item = %d",i,[[array objectAtIndex:i] integerValue]);
i = 1 ; NSLog(@"i = %d item = %d",i,[[array objectAtIndex:i] integerValue]);
NSNumber* x = [array objectAtIndex:i] ;
int* y = (int*) x ;
NSLog(@"i = %d item = %d",i,*y);
Here's the output:
2010-04-01 21:53:01.552 ArrayThing[11212:a0f] Hello, World!
2010-04-01 21:53:01.554 ArrayThing[11212:a0f] i = 0 item = 12345
2010-04-01 21:53:01.555 ArrayThing[11212:a0f] i = 1 item = 911
2010-04-01 21:53:01.555 ArrayThing[11212:a0f] i = 2 item = 12345
2010-04-01 21:53:01.556 ArrayThing[11212:a0f] i = 3 item = 911
2010-04-01 21:53:01.556 ArrayThing[11212:a0f] i = 0 item = 12345
2010-04-01 21:53:01.557 ArrayThing[11212:a0f] i = 1 item = 911
2010-04-01 21:53:01.558 ArrayThing[11212:a0f] i = 1 item = 1891989192
You can see that when I cast an NSNumber* x .... I get 1891989192. Why? Well, all we've said here is "take the first 4 bytes of the NSNumber object and print it as an integer. Why that value? We don't know without getting the code to the NSNumber class (available, however don't go there).
I hope this helps you get your head round this.