在 objective c 方法中使用 swift 定义的便利初始化
Consume a swift defined convenience init in an objective c method
我在 swift 包中定义了 NSAttributedString 的 swift 扩展,如下所示:
@objc public extension NSAttributedString {
convenience init?(html: String) {
//Do custom clean up
}
}
我已经成功导入包并将模块导入到我的 Objective-C class:
@import MySwiftPackage;
但是,当我去创建一个新的 NSAttributedString
时,我得到一个 No visible @interface for 'NSAttributedString' declares the selector 'html'
错误:
NSAttributedString *test = [[NSAttributedString alloc] html]
我哪里错了?
Objective-C 编译器希望您的初始化程序被称为 initWithHtml:
(正如@Larme 在评论中建议的那样)。
这应该有效:
NSString *myHtmlString = @"String you want to pass as 'html' parameter to your init";
NSAttributedString *test = [[NSAttributedString alloc] initWithHtml:myHtmlString];
您的扩展看起来不错,因为它被标记为 @objc
和 public
,因此不需要任何更改。
我在 swift 包中定义了 NSAttributedString 的 swift 扩展,如下所示:
@objc public extension NSAttributedString {
convenience init?(html: String) {
//Do custom clean up
}
}
我已经成功导入包并将模块导入到我的 Objective-C class:
@import MySwiftPackage;
但是,当我去创建一个新的 NSAttributedString
时,我得到一个 No visible @interface for 'NSAttributedString' declares the selector 'html'
错误:
NSAttributedString *test = [[NSAttributedString alloc] html]
我哪里错了?
Objective-C 编译器希望您的初始化程序被称为 initWithHtml:
(正如@Larme 在评论中建议的那样)。
这应该有效:
NSString *myHtmlString = @"String you want to pass as 'html' parameter to your init";
NSAttributedString *test = [[NSAttributedString alloc] initWithHtml:myHtmlString];
您的扩展看起来不错,因为它被标记为 @objc
和 public
,因此不需要任何更改。