Re: How to avoid warning?
Re: How to avoid warning?
- Subject: Re: How to avoid warning?
- From: Andy Lee <email@hidden>
- Date: Tue, 22 Jan 2013 14:28:01 -0500
On Jan 22, 2013, at 2:19 PM, Charles Srstka <email@hidden> wrote:
> On Jan 22, 2013, at 12:58 PM, Andy Lee <email@hidden> wrote:
>
>> // Or this also works (protocol).
>> @protocol AvoidCompilerWarning
>> - (id)initWithArg:(id)arg;
>> @end
>
> Really, a protocol is what you ought to be doing. Make a protocol with -initWithManager: in it, and then make all the classes that might get passed to this method comply with your protocol. Then, do this:
>
> if ([myClass conformsToProtocol:@protocol(MyProtocol)])
> myObj = [[myClass alloc] initWithManager:sel]];
> else
> myObj = [[myClass alloc] init];
>
> The advantage to this method is a simple one: Suppose some random class happens to implement a method named -initWithManager:, but that method has nothing to do with your -initWithManager: other than a coincidental title, and takes a completely different type of object. Your original code will result in unpredictable behavior in this case (and probably throw an exception leading to a crash). If you use a protocol, you'll know not just that the method responds to something named -initWithManager:, but that it's *your* -initWithManager:
Makes sense, especially since it sounds like you have enough control of the class to declare it as conforming to the protocol.
To be extra fail-safe, you might want to perform a cast to be sure the right initWithManager: gets called:
if ([myClass conformsToProtocol:@protocol(MyProtocol)])
myObj = [(id <MyProtocol>)[myClass alloc] initWithManager:self];
else
myObj = [[myClass alloc] init];
--Andy
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please 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