Objective C Syntax

Discussion in 'iOS Programming' started by nashyo, Jul 4, 2012.

  1. nashyo macrumors 6502

    nashyo

    Joined:
    Oct 1, 2010
    Location:
    Bristol
    #1
    Code:
    NSError *error;
    NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
    Why the '&' before error?
     
  2. pmau macrumors 65816

    Joined:
    Nov 9, 2010
    #2
    The & means "Take the address of an object".
    I give you another example:

    Code:
    
    void modify(int *i)
      *i = 10;
    }
    
    void test()
    {
       int i = 0;
       modify(&i);
    }
    
    
    When you want to modify a local variable that was created on the stack,
    you pass in the address of the location of the variable in memory.

    This way, the called function can modify the variable (it's memory).
     
  3. nashyo thread starter macrumors 6502

    nashyo

    Joined:
    Oct 1, 2010
    Location:
    Bristol
    #3
    I'm confused.
    If I want to modify the following pointer (which is pointing at an object)
    NSString *string = @"Hello";

    I do the following
    string = @"Bye";

    Why would I need the memory address (&string) of the object?
     
  4. pmau macrumors 65816

    Joined:
    Nov 9, 2010
    #4
    No, you don't.

    If you assign a string to an NSString *, you are assigning a pointer to a pointer.
    What you do in my example is modifying the memory where the pointer points to.

    You are not assigning a new pointer, as with NSString *, you are modifying the underlying memory.
     
  5. nashyo thread starter macrumors 6502

    nashyo

    Joined:
    Oct 1, 2010
    Location:
    Bristol
    #5
    ah got ya
    thanks
     
  6. pmau macrumors 65816

    Joined:
    Nov 9, 2010
    #6
    Maybe this helps. You might want to assign a pointer to a variable created inside a function:

    Code:
    void assign_to(NSString **str, NSString *newval)
    {
      *str = newval;
    }
    
    void blah()
    {
       NSString *hello = @"Hello";
       assign_to(&hello, @"Test")
    }
    
    
    If you pass the address, you can modify a local variable (in this case a pointer)
    The pointer you pass becomes a pointer to a pointer (note the **).

    This way you can modify a localy created pointer.
     
  7. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #7
    This is called "passing by reference."

    It's a C language thing.
     

Share This Page