1

If I declare an NSMutableString

NSMutableString *str_value;

Why do I have to declare this as a pointer (using *)? If I don't, I get a compilation error.

Could someone explain this clearly?

jscs
  • 63,694
  • 13
  • 151
  • 195
Nag_iphone
  • 967
  • 7
  • 22
  • 2
    Sorry, what is "coco"? I was going to correct it to "Cocoa" but that doesn't make sense because `NSMutableString str_value;` is an error in Cocoa (you can only declare pointers to Objective-C objects). – JeremyP May 28 '12 at 10:33
  • 2
    Using IRC English is strongly discouraged on SO. – Sergey Kalinichenko May 28 '12 at 10:33
  • possible duplicate of [Objective-C use of pointers](http://stackoverflow.com/questions/1066684/objective-c-use-of-pointers) and http://stackoverflow.com/questions/3044292/why-most-of-the-objects-we-create-in-iphone-are-pointers – jscs May 28 '12 at 18:40

2 Answers2

3

Recall that Objective C is a superset of C. When you declare a variable without * in C, it is an indication that the memory for that variable is allocated either in the automatic storage if it is a local variable, as part of its outer structure if it is a member of a structure, or in the static memory if it is a static or a global. Using the typename or a structure tag without * in a parameter list of a function indicates passing by value.

The designers of the Objective C language could have taken the Java-like route, making every class instance is a pointer without the pointer syntax, but then the readers of programs in Objective C would need to know if a name represents a typedef based on a struct or an id type to answer even the most basic questions about objects of that type, such as if it is implicitly passed by pointer or by value, if it is allocated as part of the owning structure or as a heap object pointed to by a pointer inside the structure, and so on.

To avoid this kind of confusion, designers of Objective C decided to preserve the explicit pointer syntax for id objects.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

A pointer means you are pointing / referencing to that class. Yes it will cause a compilation error, the reason for a pointer is mainly for memory. One data type (int or BOOL or float etc...) is only a few bytes, therefore it is not necessary to have a pointer. But NSMutableString and other Objective-C classes have a lot of properties and methods, with a lot of code. Therefore, since in your apps will have a lot of objects, which will use a lot of memory and thus slow down your app/decrease performance. Of course you should release the object once you make a pointer.

MCKapur
  • 9,127
  • 9
  • 58
  • 101