-
Star
(148)
You must be signed in to star a gist -
Fork
(7)
You must be signed in to fork a gist
-
-
Save steipete/9482253 to your computer and use it in GitHub Desktop.
#ifndef NS_DESIGNATED_INITIALIZER | |
#if __has_attribute(objc_designated_initializer) | |
#define NS_DESIGNATED_INITIALIZER __attribute((objc_designated_initializer)) | |
#else | |
#define NS_DESIGNATED_INITIALIZER | |
#endif | |
#endif |
If you're gonna do that, it's also a good idea to add -initWithFrame:
to your UIView subclass' header file like so:
@interface XXMyUIViewSubclass : UIView
- (id)initWithSomeCriticalData:(id)criticalData;
- (id)initWithFrame:(CGRect)frame __attribute__((unavailable("Use -initWithSomeCriticalData: instead")));
@end
This way you won't only crash at runtime, clang will emit a warning if you try to call the wrong init method.
Or if still want to crash at runtime with an assertion you can do that (and this is what I usually do):
@implementation XXMyUIViewSubclass
- (instancetype)initWithCriticalData:(id)criticalData
{
NSParameterAssert(criticalData);
// ....
}
- (instancetype)initWithFrame:(CGRect)frame
{
return [self initWithCriticalData:nil];
}
@end
I think that this can be mixed with @JaviSoto approach because is nice to warning the user with a warning but if you're designing API that need to be used by others you need to enforce this and you cannot rely on the fact that the consumer of your API will necessarily play nice.
This attribute is problematic in UIViewController subclasses. If you introduce your own init method and mark it as __attribute((objc_designated_initializer)), you'll get compiler warnings even if you do call the designated initializer of the superclass from it (i.e. [super initWithNibName:bundle:] ), since -[UIViewController initWithNibName:bundle:] is documented as designated initializer but not marked as such with this attribute.
@lukabernardi unavailable
produces a compiler error that prevents accidental misbehavior. Intentional wrongdoers will be able to skip any other check you add.
@nzhuk This is so stupid :( And when you use the unavailable
attribute, you can't redefine that method in the subclass in order to make it available again >__< .. Need.. Swift.. Now.
Interesting. It breaks with the pattern of overriding another initializer and asserting in there with a note that you must use the class' designated initializer. E.g. on a
UIView
subclass:-initWithSomeCriticalData:
, and.