Re: Noob question regarding Cocoa objects.
Re: Noob question regarding Cocoa objects.
- Subject: Re: Noob question regarding Cocoa objects.
- From: Scott Ribe <email@hidden>
- Date: Mon, 27 Nov 2006 21:39:46 -0700
- Thread-topic: Noob question regarding Cocoa objects.
> 1-I'm thinking an objective-c object's init method is basically
> equivalent to a Java's class constructor?
Roughly.
> 2-By calling init (To initialize an object) it reaches the top most
> object (NSObject) while executing all the init in the object tree?
> Let's say there's objects A through Z, and Z inherits from NSObject.
> So [a init] will call init inside B through NSObject?
No. It doesn't get called unless you call it--key difference from Java (or
C++). Same with dealloc.
> 3-Guessing my own objects (That I created) does not have to have an
> "init" - but it could be labeled as "initWithParam", etc. But I would
> have to create a logic that calls the super class init?
If you don't have your own init, then the superclass init will be called. If
you do have your own init, then you have to call the superclass init from
it. (Same with dealloc.) In Java, constructors & destructors are special in
the way that the compiler makes sure they're called for each level of the
inheritance hierarchy in a specific order. In Objective-C they're more like
plain virtual functions.
> 4-Working with objects I think of alloc and init. But some objects offer
> methods that does it for you? (Basically my last question with an example)
>
> Using NSString...
> NSString *string1 = [NSString stringWithString:@"this is a test"];
>
> Here stringWithString: actually fires off NSString init?
Yes. In Objective-C terms, stringWithString is an NSString *class* method
rather than an instance (regular) method. You should think of it as a static
method if that helps. (It's been a while since I used Java so pardon me if I
get confused and slip in some C++ terminology instead.)
One more note on something that's subtle and that people coming from
C/C++/Java tend not to see right away. The reason for those class methods is
both for a convenient way to alloc/init with common parameters and to return
an autoreleased object. You can read the rules all you want about balancing
retain/release and using autorelease for deferred release. But until you've
used it for a while, you have no clue how often those convenience methods
mean that you need to do ABSOLUTELY NOTHING about memory management--because
you call a convenience method which returns an autoreleased object, then
send it to an API or stick it in a container which will retain it.
--
Scott Ribe
email@hidden
http://www.killerbytes.com/
(303) 722-0567 voice
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden