Reputation: 2486
Could anyone tell me the difference between
NSString* string;
And
NSString* string = [NSString string];
Upvotes: 1
Views: 101
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:
nil
.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
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
Reputation: 29498
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";
}
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