K00rt
K00rt

Reputation: 49

NSString type declaration

I'm studying Objective-C. Can you tell me what is the difference (if any) between these NSString declarations?

NSString *firstString;
firstString = @"First string";

NSString *secondString = [NSString string];
secondString = @"Second string";

Upvotes: 2

Views: 1040

Answers (2)

Daniel
Daniel

Reputation: 23359

No difference as the end result.

The first string is being declared and then assigned a value via the string literal syntax (you can also do this with NSNumbers as of Xcode 4.4).

The second is being initialised as a string (empty) and then is being assigned another NSString object. In this case there are actually two NSString objects being created, the former - [NSString string] is being overwritten by the latter @"string value"

So, the first one is nil to start with and then has a value. The second had a instantiated NSString object to start and was then overwritten.

In the end both string objects are the same, but obviously you are wasting resources in the second case.

Upvotes: 1

Ben Zotto
Ben Zotto

Reputation: 71008

The second one creates two strings, and throws the first one away without using it. In this line:

NSString *secondString = [NSString string];

you are creating a new string, which isn't really useful because it's empty, and you're assigning it to secondString. Then you're assigning a different string (@"Second String") to secondString.

There's no need to do this. In either case, you can just write:

NSString *myString = @"MyString";

The syntax @"Some string here" is called a string literal, and it's a shorthand for specifying an NSString with an actual value in your code.

Upvotes: 8

Related Questions