I’ll provide a simple method and then explain how I see it, if this is incorrect, please let me know and correct me. I feel like I understand ‘self’ but still doubt my self.
-(NSString *)giveBack {
NSString *string = [NSString stringWithFormat:@"Hi there!"];
return string;
}
-(IBAction)displayIt {
NSString *object = [self giveBack];
[myView setText:object];
}
the “myView” is a UITextView object.
Now as for the ‘self’..
I’m basically saying in my -displayIt method that I’m creating a NSString object called ‘object’ and storing within it a method that returns a string which says “Hi there”.
And this method (named ‘giveBack’) is performed ON the name of my class (whatever I named the project). Is this correct?
No, you are not creating an object called
objectand then storing a method within it etc. You are creating a variable which can hold a reference to an object and storing within it a reference to an object obtained by calling a method.[Note: The following assumes you are using automatic memory management (ARC or garbage collection), no mention will be made of reference counts. If you are using manual memoery there is more to consider…]
Adding line numbers to your sample:
Declares
giveBackas an instance method of the class, to be invoked it must be called on a particular instance.The RHS (
[NSString stringWithFormat:@"Hi there!"]) calls a class method which creates an object of typeNSStringand returns a reference, of typeNSString *, to that object. The LHS declares a variable (string) which can hold a reference to an NSString object. The assignment (=) stores the reference returned by the RHS into the variable declared by the LHS.Return the value in
stringas the result of the methodDeclare an instance method called
displayItRHS: call an instance method (
giveBack) on the object instanceself–selfis a reference to the current object instance when within an instance method (in this casedisplayIt). LHS: declare a variable,objectof typeNSString *. Assignment: store the reference to anNSStringreturned by the method call on the RHS into the variable declared on the LHS.Call the instance method
setText:on the object instance referenced by the variablemyViewpassing it the reference to anNSStringfound in variableobject.