Objective C pointers

Discussion in 'iOS Programming' started by iamkoby, Aug 31, 2009.

  1. iamkoby macrumors newbie

    Joined:
    Aug 31, 2009
    #1
    Hello everyone!

    I am new to Objective-C and iPhone development but already program 5+ years in PHP with extensive OOP knowledge.
    However I am struggling to understand the concept of pointers that is extensively used in objective-C programs.

    I understand that pointers are pointing to the actual address in memory of where the variable rests but I don't understand why should I care.

    Why should I assign a variable the address and not the actual result?

    Why this:

    Code:
    NSString *myText = [[NSString alloc] init];
    and not this:

    Code:
    NSString myText = [[NSString alloc] init];

    Thanks for your answers!
     
  2. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #2
    Because those are the rules. Objective-C objects must be allocated on the heap and cannot be allocated on the stack. The compiler will object if you try it.

    Is there a good reason for this or a deep reason for this? Not really sure. I think it has to do with automatic calling of constructors and destructors. The code you showed demands a copy constructor to return an object as a struct. This exists in C++ but not in Obj-C. I guess the designers of Obj-C went for simplicity in the language design and this is a side effect.
     
  3. xsmasher macrumors regular

    xsmasher

    Joined:
    Jul 18, 2008
    #3
    Because pointers let you do some pretty powerful stuff, although it's not obvious with strings. It may be obvious with other "mutable" (changeable) objects. For example:

    Code:
    Reservation *a = [[Reservation alloc] init];
    Reservation *b = a;
    
    I have two pointers, but only one reservation object. If I call [b cancelReservation] it's the same as calling [a cancelReservation] . This is powerful stuff - it means I can pass the address of an object (just the pointer) into a method and have full control of the orginal object. It also means I can put a pointer into an array, pull it out later, and have full control of the original object.

    If objects didn't use pointers, but instead they created a copy of the object every time you did an assignment just like ints and floats do, you'd be unable to pass them to methods or store them in arrays in a useful way.
     
  4. duggram macrumors 6502

    duggram

    Joined:
    Apr 17, 2008
    #4
    Maybe this explanation of stack vs heap will help you understand why you want to use the heap when possible. Specifically the last three paragraphs.
     

Share This Page