Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSArray and NSString

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.

like image 664
Space Ghost Avatar asked Dec 03 '11 01:12

Space Ghost


2 Answers

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 pointers and objects.

Let's just look at this line:

string = [string stringByAppendingString:@"Hello"];

In this line 'string' is a pointer, not the object it points to. What this line of code is saying is: "Object currently referenced by the pointer 'string', return to me a new NSString object whose text is your text with this text added. And when I get that new NSString object I ordered make the pointer 'string' point to that object instead."

like image 171
NJones Avatar answered Sep 22 '22 15:09

NJones


string = [string stringByAppendingString:[food componentsJoinedByString:@", "]];

is the same as

NSString *tmpString = [food componentsJoinedByString:@", "];
string = [string stringByAppendingString:tmpString];

So in the example, the innermost square brackets are evaluated first, and then the outermost. Does that clarify it a bit? Thing of it like parentheses in math: (1*2*(1+2))... the innermost () get evaluated before you can determine that the real problem is 1*2*3. That is what is happening with [food componentsJoinedByString:@", "].

like image 33
Michael Frederick Avatar answered Sep 24 '22 15:09

Michael Frederick