7

A very basic question .. but really very important to understand the concepts.. in c++ or c languages, we usually don't use pointer variables to store values.. i.e. values are stored simply as is in:

int a=10;

but here in ios sdk, in objective c, most of the objects which we use are initialized by denoting a pointer with them as in:

NSArray *myArray=[NSArray array];

So,the question arises in my mind ,that, what are the benefit and need of using pointer-objects (thats what we call them here, if it is not correct, please, do tell).. Also I just get confused sometimes with memory allocation fundamentals when using a pointer objects for allocation. Can I look for good explanations anywhere?

v-i-s-h-a-l
  • 446
  • 4
  • 15
  • 6
    All objects are pointers in objective C – Groot Aug 01 '13 at 10:58
  • 5
    You have to differentiate between primitive type (for example `int`) and objects. They are different things. – trojanfoe Aug 01 '13 at 11:14
  • check this http://stackoverflow.com/questions/14991608/what-is-the-biggest-advantage-of-using-pointers-in-objectivec – Nitin Gohel Aug 01 '13 at 11:28
  • pointers allow you to modify same object/ value from many places whereas with simple assignment you destroy the previous value each time you assign – Nicolas Manzini Aug 01 '13 at 11:29
  • 1
    The OP wrote: "...pointer-objects (thats what we call them here, if it is not correct, please, do tell)." They're typically referred to as *object pointers* or *pointers to objects*. The phrase *pointer objects* doesn't map to any real Objective-C construct, and could easily lead to confusion. – jlehr Aug 01 '13 at 15:55

5 Answers5

15

in c++ or c languages, we usually don't use pointer variables to store values

I would take that "or C" part out. C++ programmers do frown upon the use of raw pointers, but C programmers don't. C programmers love pointers and regard them as an inevitable silver bullet solution to all problems. (No, not really, but pointers are still very frequently used in C.)

but here in ios sdk, in objective c, most of the objects which we use are initialized by denoting a pointer with them

Oh, look closer:

most of the objects

Even closer:

objects

So you are talking about Objective-C objects, amirite? (Disregard the subtlety that the C standard essentially describes all values and variables as an "object".)

It's really just Objective-C objects that are always pointers in Objective-C. Since Objective-C is a strict superset of C, all of the C idioms and programming techniques still apply when writing iOS apps (or OS X apps, or any other Objective-C based program for that matter). It's pointless, superfluous, wasteful, and as such, it is even considered an error to write something like

int *i = malloc(sizeof(int));
for (*i = 0; *i < 10; ++*i)

just because we are in Objective-C land. Primitives (or more correctly "plain old datatypes" with C++ terminology) still follow the "don't use a pointer if not needed" rule.

what are the benefit and need of using pointer-objects

So, why they are necessary:

Objective-C is an object-oriented and dynamic language. These two, strongly related properties of the language make it possible for programmers to take advantage of technologies such as polymorphism, duck-typing and dynamic binding (yes, these are hyperlinks, click them).

The way these features are implemented make it necessary that all objects be represented by a pointer to them. Let's see an example.

A common task when writing a mobile application is retrieving some data from a server. Modern web-based APIs use the JSON data exchange format for serializing data. This is a simple textual format which can be parsed (for example, using the NSJSONSerialization class) into various types of data structures and their corresponding collection classes, such as an NSArray or an NSDictionary. This means that the JSON parser class/method/function has to return something generic, something that can represent both an array and a dictionary.

So now what? We can't return a non-pointer NSArray or NSDictionary struct (Objective-C objects are really just plain old C structs under the hoods on all platforms I know Objective-C works on), because they are of different size, they have different memory layouts, etc. The compiler couldn't make sense of the code. That's why we return a pointer to a generic Objective-C object, of type id.

The C standard mandates that pointers to structs (and as such, to objects) have the same representation and alignment requirements (C99 6.2.5.27), i. e. that a pointer to any struct can be cast to a pointer to any other struct safely. Thus, this approach is correct, and we can now return any object. Using runtime introspection, it is also possible to determine the exact type (class) of the object dynamically and then use it accordingly.

And why they are convenient or better (in some aspects) than non-pointers:

Using pointers, there is no need to pass around multiple copies of the same object. Creating a lot of copies (for example, each time an object is assigned to or passed to a function) can be slow and lead to performance problems - a moderately complex object, for example, a view or a view controller, can have dozens of instance variables, thus a single instance may measure literally hundreds of bytes. If a function call that takes an object type is called thousands or millions of times in a tight loop, then re-assigning and copying it is quite painful (for the CPU anyway), and it's much easier and more straightforward to just pass in a pointer to the object (which is smaller in size and hence faster to copy over). Furthermore, Objective-C, being a reference counted language, even kind of "discourages" excessive copying anyway. Retaining and releasing is preferred over explicit copying and deallocation.

Also I just get confused sometimes with memory allocation fundamentals when using a pointer objects for allocation

Then you are most probably confused enough even without pointers. Don't blame it on the pointers, it's rather a programmer error ;-)

So here's...

Have fun! :-)

Community
  • 1
  • 1
  • 4
    +1 for an extraordinarily thorough answer. There out to be a special place in Stackoverflow for answers this comprehensive and well-written. – jlehr Aug 01 '13 at 15:41
  • @jlehr Thank you! I have ideas about a structural change on Stack Overflow too, but I'm afraid the recently-introduced "friendly" regime wouldn't support it... –  Aug 01 '13 at 15:54
3

Anything more complex than an int or a char or similar is usually passed as pointers even in C. In C you could of course pass around a struct of data from function to function but this is rarely seen.

Consider the following code:

struct some_struct {
    int an_int;
    char a_char[1234];
};

void function1(void)
{
    struct some_struct s;
    function2(s);
}

void function2(struct some_struct s)
{
    //do something with some_struct s
}

The some_struct data s will be put on the stack for function1. When function2 is called the data will be copied and put on the stack for use in function2. It requires the data to be on the stack twice as well as the data to be copied. This is not very efficient. Also, note that changing the values of the struct in function2 will not affect the struct in function1, they are different data in memory.

Instead consider the following code:

struct some_struct {
    int an_int;
    char a_char[1234];
};

void function1(void)
{
    struct some_struct *s = malloc(sizeof(struct some_struct));
    function2(s);
    free(s);
}

void function2(struct some_struct *s)
{
    //do something with some_struct s
}

The some_struct data will be put on the heap instead of the stack. Only a pointer to this data will be put on the stack for function1, copied in the call to function2 another pointer put on the stack for function2. This is a lot more efficient than the previous example. Also, note that any changes of the data in the struct made by function2 will now affect the struct in function1, they are the same data in memory.

This is basically the fundamentals on which higher level programming languages such as Objective-C is built and the benefits from building these languages like this.

  • "Anything more complex than an int or a char or similar is usually passed as pointers even in C" - so you generally pass `float` pointers around? Floating-point numbers are certainly more complex than `int` or `char` (even in the sense that they can hold imaginary and complex values, anyway...) –  Aug 01 '13 at 13:06
  • With regards to the context I'd count float as similar. Similar in the meaning not a composite type and just a few bytes. –  Aug 01 '13 at 13:16
1

The benefit and need of pointer is that it behaves like a mirror. It reflects what it points to. One main place where points could be very useful is to share data between functions or methods. The local variables are not guaranteed to keep their value each time a function returns, and that they’re visible only inside their own function. But you still may want to share data between functions or methods. You can use return, but that works only for a single value. You can also use global variables, but not to store your complete data, you soon have a mess. So we need some variable that can share data between functions or methods. There comes pointers to our remedy. You can just create the data and just pass around the memory address (the unique ID) pointing to that data. Using this pointer the data could be accessed and altered in any function or method. In terms of writing modular code, that’s the most important purpose of a pointer— to share data in many different places in a program.

Prazad
  • 177
  • 2
0

The main difference between C and Objective-C in this regard is that arrays in Objective-C are commonly implemented as objects. (Arrays are always implemented as objects in Java, BTW, and C++ has several common classes resembling NSArray.)

Anyone who has considered the issue carefully understands that "bare" C-like arrays are problematic -- awkward to deal with and very frequently the source of errors and confusion. ("An array 'decays' to a pointer" -- what is that supposed to mean, anyway, other than to admit in a backhanded way "Yes, it's confusing"??)

Allocation in Objective-C is a bit confusing in large part because it's in transition. The old manual reference count scheme could be easily understood (if not so easily dealt with in implementations), but ARC, while simpler to deal with, is far harder to truly understand, and understanding both simultaneously is even harder. But both are easier to deal with than C, where "zombie pointers" are almost a given, due to the lack of reference counting. (C may seem simpler, but only because you don't do things as complex as those you'd do with Objective-C, due to the difficulty controlling it all.)

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
  • what you are telling is that allocation in objective c might seem little confusing but is of great advantage when it comes to carry out complex tasks.. ?? if i got you correct.. – v-i-s-h-a-l Aug 01 '13 at 11:57
  • virtual +1 for "ARC is far harder to truly understand", and virtual -1 for "what arrays decaying to a pointer is supposed to mean" :P Also, I don't see the relevance of arrays. –  Aug 01 '13 at 12:33
  • @H2CO3 - The relevance of arrays is that that's what the OP was picking on. – Hot Licks Aug 01 '13 at 15:27
  • @BultySingh - Yes. While the Objective-C scheme is much more complex than C's malloc/free, it permits one to maintain "intellectual control" over much more complicated programs. – Hot Licks Aug 01 '13 at 15:29
0

You use a pointer always when referring to something on the heap and sometimes, but usually not when referring to something on the stack.

Since Objective-C objects are always allocated on the heap (with the exception of Blocks, but that is orthogonal to this discussion), you always use pointers to Objective-C objects. Both the id and Class types are really pointers.

Where you don't use pointers are for certain primitive types and simple structures. NSPoint, NSRange, int, NSUInteger, etc... are all typically accessed via the stack and typically you do not use pointers.