开发者

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.


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.


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.


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.


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!


Actually, C# data types are just aliases for their respective classes and that's why they can be assigned to object type. For example, int is actually a class called Int32.

As @Barry mentioned earlier, that's not the case with Objective-C.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜