Using a string as a method argument in Obj C

Discussion in 'Mac Programming' started by tw002, Jan 8, 2010.

  1. tw002 macrumors newbie

    Joined:
    Feb 23, 2009
    #1
    Hi - I'm just starting out programming in Objective C and have little experience - forgive me if this is an obvious question.

    Basically I've written a method that will set the value of a text view to the string passed to it as an argument.

    - (void)setMainMessage:(???)textToDisplay
    {

    [textView setStringValue: textToDisplay];

    }

    However I am unsure of how to pass the string that will be displayed to the method, in particular what data type to specify in the brackets above. In the past when passing an integer to a method I've simply used

    - (void)setInteger:(int)integerToDisplay;

    Using NSString in the brackets throws up errors, I'm assuming because NSString is a class itself rather than a data type.

    Any help would be really appreciated.

    Thanks in advance, Thomas.
     
  2. kpua macrumors 6502

    Joined:
    Jul 25, 2006
    #2
    Did you remember the *?

    Code:
    - (void)setMainMessage:(NSString *)textToDisplay {
    
    }
     
  3. tw002 thread starter macrumors newbie

    Joined:
    Feb 23, 2009
    #3
    Thanks - that works now, that was the problem. Why is the * used in this instance?
     
  4. Sydde macrumors 68020

    Sydde

    Joined:
    Aug 17, 2009
    #4
    NSString is a subclass of NSObject. All entities that are subclasses of NSObject are defined by an arcane data structure that cocoa uses to locate the object's data, which is somewhere else. Hence, instances of NSObject and it's subclasses are referenced by using pointers that point to that defining data structure, which is what the "*" means.
     
  5. kpua macrumors 6502

    Joined:
    Jul 25, 2006
    #5
    It really isn't all that mystical. The actual data structures for objective-C objects are essentially just structs containing all of the class's (and superclass's) ivars.

    But, for various reasons, instead of passing these objects around on the stack like you might sometimes do with C++ objects or regular C structs, they always live on the heap, which means you must access them with pointers, hence the *. To enforce this, the Objective-C compiler will generate an error when attempting to declare a class instance on the stack (without the *).
     
  6. Sydde macrumors 68020

    Sydde

    Joined:
    Aug 17, 2009
    #6
    Nor can an object have a static instance of another object as an instance variable. This is entirely sensible: the structure of a given object may not be consistent across OS or application version iterations, so a static instance of an object that has since changed would render the data structure that contains it invalid, possibly dangerously so.
     
  7. tw002 thread starter macrumors newbie

    Joined:
    Feb 23, 2009
    #7
    Thanks for your explanations, I appreciate it.
     

Share This Page