In Java, I can easily pass data using (ObjectA)objB. How can I do the similar things in Objective C? Also, why the Objective C can't return an Object, but only can return the id only? I do -(MyObj)returnMyObject{ }, but the Xcode warning me that I can't use the MyObj, but I can return the id..... -(id) returnMyObject {}.
+4
A:
The underlying model of Java and Apple's Objective C objects is really the same both have all objects on the heap and are accessed via pointers.
The difference is in Java the pointers are hidden so (ObjectA)objB is a pointer to data of type ObjectA. In Objective C the pointer is explicit and you need to say (MyObj*)returnMyObject{ }
id is a pointer to an object (so is an exception in that the pointer is implicit like Java)
Mark
2010-04-14 13:18:36
So you're always passing "pointers" around by-value.
frou
2010-04-14 16:57:23
A:
As Mark has already pointed out; all Objective-C objects require the *
at the end; it's always NSString *aString
, never NSString aString
.
This applies to casts as well; so you would have to do (MyObj *)anObject
. Note, however, that the cast doesn't actually do anything, it's merely there as a hint for the compiler.
Williham Totland
2010-04-14 13:26:03