1

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?

paul simmons
  • 5,568
  • 13
  • 51
  • 78
  • This is really a dupe of http://stackoverflow.com/questions/2189212/ To answer the C++ twist, yes -- NSString and C strings (".." is a C string) are different. Very different; an NSString is an object and stack based Objective-C objects aren't supported, hence the need for the "*". – bbum Mar 09 '10 at 05:58

2 Answers2

7

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

RyanWilcox
  • 13,890
  • 1
  • 36
  • 60
  • 3
    Well, the variables are always pointers to the objects, anyway... The objects themselves are objects. – Wooble Mar 08 '10 at 21:27
0

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.

Medran
  • 433
  • 3
  • 10