RE: Newbie Question (alloc, init, retain?)
RE: Newbie Question (alloc, init, retain?)
- Subject: RE: Newbie Question (alloc, init, retain?)
- From: "Jonathan E. Jackel" <email@hidden>
- Date: Wed, 28 May 2003 12:50:37 -0400
>
When a number gets added, I add an NSNumber set to 0.0 to
>
an NSMutuableArray, something like this:
>
>
NSNumber *foo;
>
foo = [NSNumber numberWithFloat:0.0];
>
[Numbers insertObject:foo atIndex:[Numbers count]];
>
[theTableView reloadData];
>
>
Do I have to send [[foo alloc] init]?
No. -numberWithFloat returns an instance of an NSNumber. That instance has
already been alloc'd and init'd. Moreover, since you have not called
alloc/init, copy or new, you do not "own" this object and should not release
it or autorelease it (unless you explicitly retain it yourself).
>
How do I know which
>
classes need this
>
message?
If there is no other initializer or "convenience constructor" (i.e., a class
method that returns an instance of the class) in the class, you use must use
init. Otherwise init is just one way to get an instance.
Note that any method that begins with init... (such as
NString's -initWithString:) requires alloc as well. init methods are
instance methods, so you need to send the message to an instance of the
class. +alloc provides that instance. So you would write [[NSString alloc]
initWithString:foo]. You would get almost the same thing (without ownership
of the string) by saying [NSString stringWithString:foo].
(+stringWithString is a convenience constructor.)
>
>
Also since I just add the object to the array, do I need to send [foo
>
retain]?
No, the array does that, as the NSArray docs say.
Jonathan
p.s. [Numbers addObject:foo] does the same thing as [Numbers
insertObject:foo atIndex:[Numbers count]].
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.