Re: Learning Cocoa/ObjectiveC and wondering why I had to do this.
Re: Learning Cocoa/ObjectiveC and wondering why I had to do this.
- Subject: Re: Learning Cocoa/ObjectiveC and wondering why I had to do this.
- From: "M. Uli Kusterer" <email@hidden>
- Date: Mon, 7 Mar 2005 00:52:44 +0100
At 17:02 Uhr -0600 06.03.2005, Tony Cate wrote:
I'll try. If I mess it up someone will whap me on the head
*whap* ... >:) Gee, this is fun!
NSString *result - declares the obect but it doesn't actually exist until...
Actually, it declares a *pointer* to an object. A pointer is
basically just a fancy way to say you're storing a memory address,
which is a number that the compiler lets you treat specially.
= [NSString stringWithFormat... creates the object and stuffs a
value in it. Which you already knew.
... accordingly, this call returns the address of the newly-created
string object.
NSString is a factory Class object. stringWithFormat is a message to
that factory to create a new object which, by the way, has some
specific stuff in it.
Actually, NSString is a "class cluster". stringWithFormat: is a
'factory method' that creates a new, autoreleased object of type
NSString (or of one of its subclasses, but you needn't care about
that). "factory class object" is a mix of those two that you'd better
forget right away ;-)
Since every class in ObjC also doubles as an object of type "Class"
that you can send messages to, you can send it the stringWithFormat:
message.
You could achive the same thing with this syntax:
NSString *result = [[[NSString alloc] initWithFormat:@"some
format",some object] retain];
The format you used is referred to, I believe, as a convenience
method. It's convenient because you don't have to do the 'alloc'
piece.
DANGER, WILL ROBINSON!
He meant
NSString *result = [[[NSString alloc] initWithFormat:@"some
format",some object] autorelease];
Alloc/init returns an object that you are responsible for. Which
means if you call alloc/init, you have to release or autorelease the
object whose address was returned eventually. Retaining the object a
second time means you'd have to release it a second time, which is
rarely what you want to do. So, it's convenient because it does the
alloc/init/autorelease dance for you.
BTW -- if pointers and addresses still scare you, I've written a
short piece on that topic which can be found at
http://zathras.de/angelweb/howmemorymanagementworks.htm
Be sure to let me know if it *doesn't* help you, so I can fix the
spots that aren't clear yet.
--
Cheers,
M. Uli Kusterer
------------------------------------------------------------
"The Witnesses of TeachText are everywhere..."
http://www.zathras.de
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden