【问题标题】:Crashed when I call objective-c method in swift当我在swift中调用objective-c方法时崩溃
【发布时间】:2018-01-15 17:51:01
【问题描述】:

这是崩溃信息:

LMAlertView是一个三部分使用objective-c,我用了很长时间,一切都很顺利。但是当我在swift中使用它时,发生了一些奇怪的事情:当我编码init时,Xcode警报为我和我只需点击 Enter 键,因此整个 func 自动完成。但是 Xcode 显示的 func 不是 LMAlertView 中的真正 func:

这是LMAlertView中的源代码:

- (id)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION;

如您所见,otherButtonTitles 的参数在我的代码中丢失了,它使用 Xcode 自动完成。

如果我将otherButtonTitles 参数添加到我的代码中,它将构建失败。

我该如何解决这个问题?如果有人能解释一下,那就太好了。

【问题讨论】:

    标签: ios objective-c swift


    【解决方案1】:

    在 Swift 中尝试类似

    let alertView = LMAlertView(title: "YourTitle",message:"your Message" delegate:nil cancelButtonTitle:"cancel" otherButtonTitles:nil)
    

    【讨论】:

    • 修复它,插入 "," ,我做到了,然后 Xcode 显示:"type of expression is ambiguous without more context"
    • 我不知道为什么 Xcode 没有给我一个完整的 func 警报信息。
    • 您是否在桥接头中添加了LMAlertView?
    • 这个项目是用oc写的,我在PCH文件中#import "LMAlertView.h",在桥接文件中我导入PCH文件。
    【解决方案2】:

    您需要更改LMAlertView的源代码。

    首先,在 LMAlertView.h 中,添加一个新的 init 方法,其中包含其他标题的数组(不要忘记注释旧的):

    //- (id)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION;
    - (id)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSArray *)otherButtonTitles;
    

    第二,在LMAlertView.m中,实现新的init方法(不要忘记注释旧的):

    - (id)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSArray *)otherButtonTitles {
        self = [super init];
        if (self) {
            _delegate = delegate;
            [self setupWithTitle:title message:message cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles];
        }
        return self;
    }
    

    最后,您可以像这样快速调用它,而不会崩溃:

    let alertView = LMAlertView(title: "a title", message: "a message", delegate: self, cancelButtonTitle: "cancel", otherButtonTitles: ["other title1","other title2"])
    //......
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-20
      • 2014-09-10
      • 1970-01-01
      • 2021-11-26
      • 2022-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多