Ben_hawk
Ben_hawk

Reputation: 2486

Objective-c syntax confusion

Could anyone tell me the difference between

NSString* string;

And

NSString* string = [NSString string];

Upvotes: 1

Views: 101

Answers (3)

jtbandes
jtbandes

Reputation: 118681

Just like in C,

NSString *string;

declares the variable (pointer) string but gives it no value. This means you can't use the variable until you've initialized it, for example by doing string = @"foo";.

Note:

  • If this is an instance variable it actually will be initialized automatically — to nil.
  • If you use the variable somewhere in your code without initializing it in every possible branch (if conditions, etc.) then the compiler will complain. To avoid this you could just set it to an empty string or nil to start with.

The line

NSString *string = [NSString string];

uses the +string method of the NSString class to create an empty string. You could also use @"".

(Further note: I recommend using NSString *string instead of NSString* string because the former hides a syntax idiosyncrasy: NSString *string1, *string2; is the correct way to declare multiple pointer variables on one line.)

Upvotes: 3

zaph
zaph

Reputation: 112857

NSString *string;

Creates a pointer but not a string object (instance). It may be initialized to nil or not depending on where it is an compiler options. In other words it creates a place (memory storage) for a pointer to an NSString bot no NSString object.

NSString *string = [NSString string];

Creates an empty string object (instance) and a pointer to it.

Upvotes: 1

Michael Robinson
Michael Robinson

Reputation: 29498

NSString *string;

The first your just declaring that there will be a variable that is an NSString, named string, but not initializing it.

You might do this when you want a string to contain one of a range of values, determined by some condition:

NSString *string;

if (condition) {
    string = @"This condition";
} else {
    string = @"That condition";
}

NSString *string = [NSString string];

The second you are doing all of the above, with the additional step of initializing your string variable to an empty string.

You might do this when you want a string to contain a specific single value:

NSString *string = @"There are no conditions"

Upvotes: 2

Related Questions