The book I’m currently reading has me write the following code :
-(IBAction)displaySomeText:(id)sender {
NSString *cow = @"Milk";
NSString *chicken = @"Egg";
NSString *goat = @"Butter";
NSArray *food = [NSArray arrayWithObjects:cow, chicken, goat, nil];
NSString *string = @"The shopping list is: ";
string = [string stringByAppendingString:[food componentsJoinedByString:@", "]];
[textView insertText:string];
}
I understand somewhat how arrays work but I need help understanding the following code
string = [string stringByAppendingString:[food componentsJoinedByString:@", "]];
I have never ever seen an instance where this is possible.
He has me create a ‘string’ object, from the NSString class, and then I’m doing this
string = [string stringByAppendingString:];
I’m confused. I have never seen an example where I create an object and then perform a method on the same object and store it in that exact same object.
For example, I know I can do this
NSSound *chirp;
chirp = [NSSound soundNamed:@"birdChirp.mp3"];
the above makes sense because I used the created object and performed a class method on it..
but I always assumed that the equivalent of the following code was NOT possible
chirp = [chirp methodNameEtc..];
I hope I explained my question well. If not I could always elaborate further.
I think this is the heart of your question “I’m confused. I have never seen an example where I create an object and then perform a method on the same object and store it in that exact same object.”
To answer that question, your not actually ‘storing it in the exact same object‘. What you are doing is confusing
pointersandobjects.Let’s just look at this line:
string = [string stringByAppendingString:@"Hello"];In this line ‘string’ is a
pointer, not theobjectit points to. What this line of code is saying is:“
Objectcurrently referenced by thepointer‘string’, return to me a newNSStringobjectwhose text is your text with this text added. And when I get that newNSStringobjectI ordered make thepointer‘string’ point to thatobjectinstead.”