Subclass Objective-C Classes in Swift
I am using MWPhotoBrowser in a Swift project. One problem is that the MWPhotoBrowser subclass won't compile with an error like this:
: 0: error: cannot override 'init' which was marked inaccessible
My code is here:
class BrowseController: MWPhotoBrowser {
override init() {
super.init()
initialize()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initialize()
}
...
And here are all the initializers of the parent class:
// Init
- (id)initWithPhotos:(NSArray *)photosArray __attribute__((deprecated("Use initWithDelegate: instead"))); // Depreciated
- (id)initWithDelegate:(id <MWPhotoBrowserDelegate>)delegate;
Overriding these initializers in my subclass doesn't help. But if I subclass MyBrowser in Objective-C and then subclass that class, everything works fine.
@interface MyBrowser : MWPhotoBrowser
- (id)init;
@end
@implementation MyBrowser
- (id)init {
if (self = [super init]) {}
return self;
}
@end
class BrowserController: MyBrowser {
...
I am using Xcode 6.1. Is this a Swift bug or am I missing something about Swift-intializers? Thank!
source to share
Chanitorn's answer is not entirely correct because it is initWithDelegate:
not the designated initializer for MWPhotoBrowser, init:
and initWithCoder:
. The trick is to add them to the public header of MWPhotoBrowser and specify them asNS_DESIGNATED_INITIALIZER
- (id)initWithCoder:(NSCoder *)decoder NS_DESIGNATED_INITIALIZER;
- (id)init NS_DESIGNATED_INITIALIZER;
source to share
The strictness of fast initializers seems to be causing the problem. try using NS_DESIGNATED_INITIALIZER to define a designated initializer in your objective-c library class to resolve this issue.
- (id)initWithPhotos:(NSArray *)photosArray __attribute__((deprecated("Use initWithDelegate: instead"))); // Depreciated
- (id)initWithDelegate:(id <MWPhotoBrowserDelegate>)delegate NS_DESIGNATED_INITIALIZER;
source to share