Women in Technology

Hear us Roar



Article:
  Memory Management in Objective-C
Subject:   (Q) interchangeable pointers and objects
Date:   2001-07-31 07:23:03
From:   justinarmstrong
Response to: (Q) interchangeable pointers and objects

is this the line that is confusing you?


[textField setStringValue:[NSString stringWithCString:"Hello"]];


remember how the square brackets show
the nesting of message sends.


the first message sent is 'stringWithCString:'
which goes to the NSString *class* object.
A class object is a special kind of object
that knows how to create other objects,
in this case instances of NSString.
So, as a result of this stringWithCString
message is a new NSString instance that
in this case contains the text "Hello".


This new string is then passed as an
argument to the setStringValue: message
which is sent to a textField.


there isn't really any voodoo compiler
stuff going on behind your back.
"NSString" is just the name of a global
object that happens to be a class object.


if you look at
NSString* string = [NSString stringWithCString:"hello"];


this creates a variable called 'string'
which is a pointer to an instance of
'NSString'. This pointer is then initialized
to a new instance of the class NSString.


spend a while looking at it, ObjC takes
some getting used to, but is in fact entirely
sensible!



Full Threads Oldest First

Showing messages 1 through 1 of 1.

  • (Q) interchangeable pointers and objects
    2003-12-09 17:35:27  anonymous2 [View]

    If you want to gain a better understanding of the relationship between a class and its instances, and find out what is happening "behind the scenes," I suggest you read the article below.

    http://www.macdevcenter.com/lpt/a/2432

    It takes careful reading, but is very valuable. Keep in mind that all objective-c objects are manipulated as pointers to an object that exists somewhere else in memory--the id type is implemented as a pointer to a class or instance. Classes are also objects. This is why a message can be sent to a class, as in the NSString initialization example. In [NSString stringWithCString:"hello"], NSString is actually a pointer to the object representing the NSString class, not to the NSString type. (I conjecture that the NSString type is actually not a type but a struct--structs behave somewhat like a typedef under certain circumstances). Maybe I've clarified things, or maybe I've just written an incomprehensible bunch of jargon. I can't tell. If this helps, good. If not, ignore it.