In c# I can declare object o;
then I can assign o=(float)5.0;
or o="a string."
Is there an equivalent for Objective-C? I tried to use id
but it does not take primitive type like float or integer. Thanks for helping.
views:
158answers:
4There isn't really such a thing. You can use NSNumber
or NSValue
to handle native data types as objects. NSString
will do strings. You can assign all of those to an id
typed variable, but you'll need to create them with the correct class's init
methods.
You are correct, id
only works for ObjC object references. If you want to reference an int with an id reference, you need to box it into an NSNumber
. Incidentally, C# is boxing those primitives too, it's just doing it automatically.
Objective-C doesn't have a "unified type system" in the words of the CLR. In other words, as a superset of C, Objective-C's primitive types are different beasts altogether than object instances. The id
type can store references (really pointers in the OS X/iPhone Objective-C runtime) to any object instance. C's primitive types (e.g. int
,float
,etc.) must be wrapped in NSValue
or NSNumber
to be assigned to type id
. Of course, this is exactly what the C# compiler is doing. It's just that in C#, you don't have to do the (un)boxing conversion explicitly.
Pretty soon, code like
float val;
id obj = [NSNumber numberWithFloat:val];
...
float v = [obj floatValue];
will become second nature, if unfortunately verbose by modern standards.
Back in my day we had to walk 15 miles in the snow, uphill, to use void pointers. Oh, and we didn't have StackOverflow!