On Jan 22, 2013, at 8:28 PM, Andy Lee <ag...@mac.com> wrote: > 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];
This only works for classes that actually declare themselves to be in conformance with this protocol, though. Even if a class implements all the methods in a protocol, conformsToProtocol: will return NO if it doesn't have the protocol name on the @interface (or on the @implementation line). IMO the nicest way to do this (if you can't make all your classes conform to the protocol by declaring them as @interface Foo : NSObject <UKCanInitWithManagerProtocol>, which would definitely be the cleanest approach), would be: @protocol UKCanInitWithManagerProtocol -(id) initWithManager: (Foo*)inManager; @end ... if( [myClass respondsToSelector: @selector(initWithManager:)] ) myObj = [(id<UKCanInitWithManagerProtocol>)[myClass alloc] initWithManager: self]; else myObj = [[myClass alloc] init]; Though I would recommend choosing a different name. E.g. -initWithBarManager: if the manager class is called UKBarManager. "Manager" alone is too generic a word, and someone might have declared it in ObjC++ and taking a C++ object and then you're screwed. Cheers, -- Uli Kusterer "The Witnesses of TeachText are everywhere..." http://www.zathras.de _______________________________________________ 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