On Jan 22, 2013, at 2:19 PM, Charles Srstka <cocoa...@charlessoft.com> wrote:
> On Jan 22, 2013, at 12:58 PM, Andy Lee <ag...@mac.com> 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 (Cocoa-dev@lists.apple.com) 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: https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com