What is the difference between
char *foo
and
(char *) foo
in Objective-C? 开发者_运维技巧
Here is an example for both scenarios:
1. @interface Worker: NSObject { char *foo; }
2. - initWithName:(char *)foo
There are two places your first expression can appear. The first is as a variable definition. By itself, char *foo
is defining a variable - a pointer to char
named foo
. In the context of a function definition it defines the type of one of the function's parameters:
void function(char *foo)
Declares a function that takes a single char *
argument and indicates that that argument will be referred to by the name foo
in the context of the function.
There are also a couple of explanations for your other expression. The first is in the case of a method definition, which is similar to the function declaration above:
- (void)method:(char *)foo
Declares an instance method taking a single argument, in this case of type char *
and named foo
. It could also appear as the return type of the method:
- (char *)foo
Another case is as a typecast:
void *foo;
char *bar = (char *)foo;
In which case the expression typecasts foo
from a void pointer to a char
pointer and assigns the value to bar
.
Edit:
For your particular examples:
@interface Worker: NSObject
{
char *foo;
}
This example is declaring an instance variable named foo
. It has type char *
.
- initWithName:(char *)foo
This example is declaring an instance method taking one parameter named foo
of type char *
.
+ (char*) foo; // "static" function returning a variable of type char* - (char*) foo; // member function returning a variable of type char* // ... { // ... char* foo; // variable of type char* // ... } // ...
EDIT
- (void) whatever: (char*)foo; // member function, with // parameter foo of type char* // ... { // ... char* bar = (char*) foo; // casting variable foo to type char* // ... } // ...
精彩评论