views:

158

answers:

4

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.

+3  A: 

There 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.

Carl Norum
+3  A: 

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.

Matt Greer
+11  A: 

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.

Barry Wark
Thanks Barry. I ended up doing exactly what you suggested. Since I need to store a mix bag of c type data in an array, it there an easy way to detect the data type once it is converted into NSNumber?
Wayne Lo
`NSNumber` is a subclass of `NSValue`, so you can use `-objCType` and do C-string comparisons to determine the actual number type... pretty old school, but it works. This is a case where Objectie-C's desire to feel dynamically typed and C's static typing run afoul of each other.
Barry Wark
+2  A: 

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!

anthony
not answering the question but I like it :)
Ben
I like this, but I have to -1 because doesn't answer the question. ( try making CW and I'll upvote it then )
OscarRyz
+1 because the World is a better place with some humour in it.
JeremyP
In my mind void * is actually the closest thing to a base type such as 'object' in c#. You _could_ use it to reference an arbitrary value, but I wouldn't seriously suggest that. Therefore, my answer is not serious.
anthony
Also, I think it's a great thing that we're at a point where a unified type system is generally considered to be a good thing. Java blew it.
anthony