2

// I have an array

NSMutableArray *anArray = [[NSMutableArray allot] init];

// I want to add a string object. I can add it either using this:

NSString *aString = @"A random string";
[anArray addObject:aString];

// But I can also do this:

[anArray addObject:@"A random string"];

For the second option, this creates a new string object. I can't explicitly access this object, but I can access it with the array with objectAtIndex:. But why would one ever use the first option then?

3
  • The name of the variable might indicate what the string represents better. If the string is long you might be able to format the code better the first way. In reality they do identical things - the compiler will optimize out any differences, so do whichever is more readable. Commented May 27, 2015 at 21:06
  • Oh, thank you, that was a complete answer I don't know why you put it as a comment! Commented May 27, 2015 at 21:10
  • zaph had already answered it and I was just adding a little bit of info. Commented May 28, 2015 at 4:09

1 Answer 1

1

In both cases @"A random string" is created at compile-time. Personally I used the single statement. It really does not make any difference, the compiler will most likely optimize away the temporary aString.

As for "But why would one ever use the first option then?" let me ask why anyone would wear black instead of brown shoes? Personal preference.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.