Search code examples
c#objective-ctypesambiguity

what is the equivalent of object in C# for objective C?


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.


Solution

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