开发者

Can someone explain to me what (NSString *) means with Obj-C?

I just started with Objective-C and I would like to understand the meaning of the following lines of code as I see it everywhere in objective-c but开发者_C百科 I'm not quite getting it 100%:

- (id)initWithName:(NSString *)name;

I understand that the above line is a instance method passing one argument, what I don't understand is (NSString *)name.

another example is:

-(NSString *)name;

or

person.height = (NSObject *)something;

Thanks for your help


In this line:

- (id)initWithName:(NSString *)name;

(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.

In this example:

person.height = (NSObject *)something;

something a little different is happening: (NSObject *) is again specifying a type, but this time it's a "type casting" operation -- what this means is to take the "something" object reference (which could be an NSString, NSNumber, or ...) and treat it as a reference to an NSObject.


update - When talking about Objective-C objects (as opposed to primitive types like int or float), everything's ultimately a pointer, so the cast operation means "take this pointer an X and treat it as if it's pointing to a Y". For example, if you have a container class (like NSArray) that holds generic NSObjects, but you know that the the objects are actually strings, you might say:

NSString *myString = (NSString *)[myArray objectAtIndex:0];

which means "retrieve the first object from the array, treating it as a string".

The cast is not actually converting the value, it's just a way of saying to the compiler "hey, I know that I'm assigning an X to a Y here, so don't give me a warning about it".


- (id)initWithName:(NSString*)name;

Is a signature of a method that takes one parameter called name which is a pointer to NSString.

-(NSString *)name;

Is an accessor method called name that returns pointer to NSString.

person.height = (NSObject *)something;

Typecasts something to a NSObject pointer and then it is assigned to person.height property.

See more explanation in Learning Objective-C: A Primer


- (id)initWithName:(NSString *)name;
    -----------------------------------------
    '-'  means its an instance method (+ is used for static methods)
    '(id)' is the return type    
    'initWithName' is the function name, the name implies its a constructor
    ':' start of parameter
    '(NSString*)' parameter type
    'name' parameter name

its the equivalent of

(id)initWithName( NSString* name )


(NSString *)name

is saying that a variable name is a pointer * to a NSString object. Its a pointer because the name variable isn't the string but rather it is just the address in memory for that string.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜