Re: Memory management question
Re: Memory management question
- Subject: Re: Memory management question
- From: Andreas Mayer <email@hidden>
- Date: Sun, 28 Mar 2004 00:56:14 +0100
Am 27.03.2004 um 19:00 schrieb Jerry Krinock:
What's the effective difference between these two expressions?
The difference is that [self foo] sends the foo message to the object
itself which might *not* be of class FooClass but could of a subclass
of it; so [self foo] possibly doesn't lead to the execution of your foo
method and subsequently might not return the foo instance variable.
Example:
@interface ClassA : NSObject
{
id foo;
}
- (id)foo
{
return foo;
}
- (void)setFoo:(id)newFoo
{
[foo autorelease];
foo = [newFoo retain];
}
- (void)checkFoo1 // first version - accessing the instance variable
directly
{
if (foo != nil) {
NSLog(@"foo is valid");
} else {
NSLog(@"foo is invalid");
}
}
- (void)checkFoo2 // second version - using accessor method
{
if ([self foo] != nil) {
NSLog(@"foo is valid");
} else {
NSLog(@"foo is invalid");
}
}
@end
@interface ClassB : ClassA
{
}
- (id)foo
{
// we decided that foo is of no use in this special subclass
return nil;
}
@end
Suppose something like this happens somewhere in the code:
ClassA *someObject = [[ClassB alloc] init]; // might be a return value
from some opaque method
[someObject setFoo:someOtherObject];
Now
[someObject checkFoo1];
will log "foo is valid" while
[someObject checkFoo2];
will result in "foo is invalid".
It is up to you to decide, if subclasses should be able to overwrite
the value of your instance variables. Generally they should because
that's the point of object oriented design.
I admit though, that I'm not always doing the "right thing" either ...
:-/
Andreas
_______________________________________________
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.