Re: observing dealloc
Re: observing dealloc
- Subject: Re: observing dealloc
- From: Wincent Colaiuta <email@hidden>
- Date: Tue, 29 May 2007 17:32:40 +0200
El 29/5/2007, a las 16:59, James Bucanek escribió:
Use static variables.
You could have fifty classes that all implement ...
static id sFoo; // really stupid name
...
@implementation AnyClass
+ (void)initialize
{
// if (sFoo==nil) -- pointless test; initialize only runs once
sFoot = [[NSObject alloc] init];
}
Although Apple's docs indicate that the runtime will send the
initialize message once per class, that doesn't mean that the test in
the above code is pointless. As the example code below demonstrates,
the super class initialize method will be called for subclasses if
they don't implement it, which means that the same static variable
can end up getting used in both cases. Also, even though the docs say
that you "typically" don't need to call +[super initialize], there
are plenty of examples of code out in the wild which do exactly that
and so you may need to be aware of that also if you're writing
frameworks or code which may be used by others.
Example:
#import <Foundation/Foundation.h>
@interface Foo : NSObject {}
@end
@implementation Foo
+ (void)initialize
{
static int count = 0;
NSLog(@"+[%@ initialize]: %d", NSStringFromClass([self class]),
count++);
}
@end
@interface Bar : Foo {}
@end
@implementation Bar
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
[Foo class];
[Bar class];
[pool release];
return 0;
}
Output:
+[Foo initialize]: 0
+[Bar initialize]: 1
_______________________________________________
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