Re: Protocols and the +initialize class method
Re: Protocols and the +initialize class method
- Subject: Re: Protocols and the +initialize class method
- From: Fritz Anderson <email@hidden>
- Date: Fri, 23 Aug 2013 08:28:13 -0500
On 23 Aug 2013, at 4:49 AM, Kevin Meaney <email@hidden> wrote:
> I have a protocol where I would like to include the class method +(void)initialize as being required. This way all classes that conform to the protocol have to implement initialize as part of the protocol. I suppose I'm wondering if anyone perceives any problem with doing this?
>
> For example, will including +initialize as a required protocol method interfere with objective-c automatically calling the initialize method before the class is used for the first at runtime.
The threshold question is whether the compiler will enforce the protocol as you wish. This is easy to test. The following code passes analysis and runs with no problem:
-----
#import <Foundation/Foundation.h>
@protocol NeedsInitialize <NSObject>
+ (void) initialize;
- (void) mandatoryInstance: (NSString *) str;
@end
@interface NAImplementor : NSObject <NeedsInitialize>
- (NSInteger) anotherMethod;
@end
@implementation NAImplementor
- (void) mandatoryInstance:(NSString *)str
{
NSLog(@"%s gets string %@", __PRETTY_FUNCTION__, str);
}
- (NSInteger) anotherMethod
{
NSLog(@"%s sending -mandatoryInstance:", __PRETTY_FUNCTION__);
[self mandatoryInstance: @"NAImplementor sends mandatory"];
return 12;
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
NAImplementor * instance = [[NAImplementor alloc] init];
NSLog(@"%s implementor returns %li", __PRETTY_FUNCTION__, (long)[instance anotherMethod]);
}
return 0;
}
-----
As I understand it, you want to require NAImplementor to have +[NAImplementor initialize]. This code passes without this happening. It seems NSObject implements +initialize, which is good enough to satisfy the protocol.
"Incomplete Objective-C Protocols," GCC_WARN_ALLOW_INCOMPLETE_PROTOCOL (Warn if methods required by a protocol are not implemented in the class adopting it. Only applies to Objective-C.), which is the closest warning I can find in short order to what you want, is set YES, so if the warning worked as you hope, it should have triggered.
You might have the +load method of the class introspect to see if it implements +initialize, and throw an exception, but that requires a class hierarchy that defeats the purpose of a protocol.
— F
_______________________________________________
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