Skip to content

Instantly share code, notes, and snippets.

@hborders
Created October 15, 2013 20:50
Show Gist options
  • Save hborders/6998448 to your computer and use it in GitHub Desktop.
Save hborders/6998448 to your computer and use it in GitHub Desktop.
Demonstrates problem with static methods
@interface Foo : NSObject
+ (void)bar;
@end
@implementation Foo
+ (void)bar {
}
@end
@interface Baz : NSObject
@end
@implementation Baz
+ (void)initialize {
if (self == [Baz class]) {
[self bar]; // No known class method for selector 'bar'. Yay!
}
}
- (id)init {
self = [super init];
if (self) {
[[self class] bar]; // No errors. Boo!
}
return self;
}
@end
@numist
Copy link

numist commented Oct 15, 2013

There are at least two code smells here:

  • Sending messages to self in -init and +initialize is fragile due to the potential for side effects on an object that's not fully initialized.
  • If Baz was subclassed, +bar may not be what you want anymore. The call at :30 should explicitly refer to Baz instead of [self class].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment