Re: dealloc and instance variables
Re: dealloc and instance variables
- Subject: Re: dealloc and instance variables
- From: Graeme Mathieson <email@hidden>
- Date: Sun, 23 Nov 2003 08:55:05 +0000
On 23 Nov 2003, at 07:52, Jvrn Salewski wrote:
Whenever you say init, copy or retain you must say release.
Right, that makes sense. Thanks.
// if sString is an immutable NSString
// a simple retain is sufficient.
That brings up another thing I'm not entirely sure about. Surely
somebody could in fact pass in an NSMutableString and, despite the fact
my object thinks its immutable, merrily mess around with my object's
data without going through the appropriate accessors? I guess the only
way to be sure would be something along the lines of:
- (id)initWithString:(NSString *)aString
{
if((self = [super init])) {
if([aString isMemberOfClass:[NSString class]]) {
baz = [aString retain];
} else {
baz = [aString copy];
}
}
return self;
}
Or is that being too paranoid? Likewise, if my class internally uses
an NSMutableArray to store some data, and I would like an accessor
which gives (read-only) access to that array, is it sufficient to do:
@interface FooBar
{
NSMutableArray *attributes;
}
- (NSArray *)attributes;
@end
[ ... ]
- (NSArray *)attributes
{
return attributes;
}
or should I do:
- (NSArray *)attributes
{
return [NSArray arrayWithArray:attributes];
}
to be sure?
Putting this together with your previous question. You could have an
ivar
id foo;
in your FooBar class and say foo = nil; in your init method. Since
FooBar is
responsible for the variable foo, it must [foo release]; it in its
implementation of dealloc, allthough it might be actually nil.
... which, coincidentally, was where most of the instances of 'if(foo)
[foo release];' were to be found in a previous incarnation of my code.
:-)
Thanks for your assistance; I'm feeling far more enlightened with this
new-fangled Cocoa than I was earlier this morning...
--
Mail, MSN Messenger & Jabber: mathie [at] endless [dot] org [dot] uk
AIM: MathieEndless, Blog:
http://www.endless.org.uk/blog/
OpenPGP Fingerprint: 0F38 5000 999F 0644 76D6 968D A945 916E AD30 4A1A
_______________________________________________
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.