What is the meaning of this Objective-C syntax?
Would someone please clarify what the difference in these开发者_运维百科 two snippets would be?
I know this is instantiation:
Class *myClass = [[Class alloc] init] ....etc
but what exactly is this?
(Class *)myClass .....etc
Thanks
The second snippet is either a cast or a parameter to a method. Neither have anything to do with instantiation.
If (Class *)myClass
occurs in a method declaration, it just defines what type the parameter to the method should be. For example, - (void) method:(Class *)myClass
is a method that returns void and takes one argument, of type Class*
.
If (Class *)myClass
occurs in other code, it's a cast. Basically it says to reinterpret myClass
as a pointer to an object of type Class
, regardless of what its type really is. It's like casting with numbers - if x
is an int
, (float)x
casts it as a float
so you can use it in floating-point arithmetic.
Generally speaking, I'd caution you against using casting heavily with Objective-C objects. One place you will see things like this is in casting NS objects to CF objects, as in (CFURLRef)[NSURL fileURLWithPath:path]
. But most often objects of different types will not cast properly.
Also, you have an error in your first snippet. It would actually be [[Class alloc] init]
. You must call alloc
and then init
. And [init]
is meaningless - it doesn't fit the [object method]
syntax of Objective-C at all.
The first one, given correct syntax is instantiating, as you say.
The second one is casting a variable "myClass" to a pointer to an instance of the Class object.
The second snippet is a C-style cast. It effectively tells the compiler to treat myClass as a value of type Class* regardless of its declared type. Without the rest of the snippet (and the preceeding declaration of myClass), it's impossible to say why you would want to use the cast or what effect it would have.
精彩评论