user192936
user192936

Reputation:

Why Obj-C Strings are always *NSString not NSString

Is it normal, that declaring

NSString c="a sample string";

cannot work, and must declare it as NSString* ? It's different from C++ strings, am I right? Can it be generalized to other Obj-C objects?

Upvotes: 1

Views: 419

Answers (2)

Medran
Medran

Reputation: 443

This goes back to proper code design even in C++, if you had a C++ string class and created it without a pointer than the entire data set would be stored on the stack, and when that variable would be copied all the members would be copied. In c++ there is operator overloading to make this work, so a class can override the assignment operator to properly copy the data of the class, in objective-c and normal c there is no operator overloading. So if you had... NSString a,b; and you did a = b; it would copy the value of all the members, which could be pointers to allocated strings in memory. In c++ your string class can overload the assignment so that when you do a = b it actually allocates a copy of the string into a instead of just a pointer to b's data. The reason this is important is imagine editing b's data, then possibly a would be partially updated as well(however the update wouldnt necesarily be correct depending on all the members that were changed in b, a could become partially invalid). By forcing things to be a pointer its very clear that NSString *a,*b; a = b. You know that a is just a pointer to b and if b is changed a is also changed.

Upvotes: 0

RyanWilcox
RyanWilcox

Reputation: 13972

Because Objective-C objects are always pointers (which includes NSString)

Upvotes: 6

Related Questions