Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

objective-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 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

like image 762
Ole Media Avatar asked Jan 23 '23 00:01

Ole Media


2 Answers

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".

like image 183
David Gelhar Avatar answered Jan 30 '23 08:01

David Gelhar


- (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

like image 33
stefanB Avatar answered Jan 30 '23 08:01

stefanB