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
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 NSObject
s, 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With