Re: Hiding superclass methods
Re: Hiding superclass methods
- Subject: Re: Hiding superclass methods
- From: Andy Lee <email@hidden>
- Date: Thu, 9 May 2002 18:40:14 -0400
At 4:36 PM -0500 5/9/02, Brock Brandenberg wrote:
Is there a way in Obj-C to hide a superclass method so that compiler
checking would catch/flag any access to that method? I have an
NSView subclass that is instantiated in code at runtime that has a
custom initWithFrame:data: method that, in turn, calls the
initWithFrame: method. I'd like to prevent my accidental use of the
standard initWithFrame method, if possible, but haven't found any
relevant information in the Obj-C book.
It is acceptable practice to do this, or should I explicitly call an
additional initializer after my [[obj alloc] initWithFrame:] calls?
Let me check whether I understand correctly. You do not want an
instance of your view class (I'll call it BrockView) to call the
inherited -initWithFrame:, *except* within its -initWithFrame:data:
method?
You can't get the compiler to warn you about this (at least not by
any reasonable means). But if you apply the designated-initializer
concept, it shouldn't be a problem in practice. It sounds like
-initWithFrame:data: should be the designated initializer of
BrockView:
@interface BrockView : NSView
// This method calls -initWithFrame:data:, passing a default
// value for the second argument.
- (id)initWithFrame:(NSRect)frameRect;
// Designated initializer. This method does [super initWithFrame:].
// It is the only place in BrockView where [super initWithFrame:]
// is called. <=== just make sure this is true
- (id)initWithFrame:(NSRect)frameRect data:(NSData *)viewData;
@end
If there is really, really no appropriate default value for viewData,
you can check it at runtime -- as you should anyway, to make sure the
caller isn't passing in a bad value:
@implementation BrockView
- (id)initWithFrame:(NSRect)frameRect
{
// NSData *defaultData =
// [[NSData alloc] init]; <== not acceptable for some reason
// return [self initWithFrame:frameRect
data:defaultData];
return [self initWithFrame:frameRect
data:nil];
}
- (id)initWithFrame:(NSRect)frameRect data:(NSData *)viewData
{
if (! viewData)
{
// Print a warning message or raise an exception
// or substitute a valid value for viewData.
}
if (self = [super initWithFrame:frameRect])
{
// Do further initialization using viewData.
}
return self;
}
@end
Note that nothing stops someone from adding a category to your class
with a method that calls [super initWithFrame:] and bypasses your
official init logic, but that wouldn't be accidental, and such a
person would be asking for trouble.
(Disclaimer: all the above code is untested.)
HTH,
--Andy
_______________________________________________
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.