2016-11-06 50 views
1

我已經在一個swift項目中導入了這個Objective-C類。 MMLANSCanner.hinitWithDelegate for Objective-C類

#import <Foundation/Foundation.h> 

@class Device; 
@protocol MMLANScannerDelegate; 
@protocol MMLANScannerDelegate <NSObject> 
@required 
- (void)lanScanDidFinishScanningWithStatus:(MMLanScannerStatus)status; 
- (void)lanScanDidFailedToScan; 
@optional 
- (void)lanScanProgressPinged:(float)pingedHosts from:(NSInteger)overallHosts; 
@end 

#pragma mark - Public methods 
@interface MMLANScanner : NSObject 
-(instancetype)initWithDelegate:(id <MMLANScannerDelegate>)delegate; 
@property(nonatomic,weak) id<MMLANScannerDelegate> delegate; 
@property(nonatomic,assign,readonly)BOOL isScanning; 
- (void)start; 
- (void)stop; 
@end 

我成功創建了橋接報頭,使MainVC.Swift符合MMLANScannerDelegate。 然後我試着用代理self初始化MMLanScanner。

import UIKit 
import Foundation 

class MainVC: UIViewController, MMLANScannerDelegate { 

    var presenter = MMLANScanner(delegate:self) 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Do any additional setup after loading the view. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    func lanScanDidFindNewDevice(_ device: Device!) { 

    } 

    func lanScanDidFailedToScan() { 

    } 

    func lanScanDidFinishScanning(with status: MMLanScannerStatus) { 

    } 

    func lanScanProgressPinged(_ pingedHosts: Float, from overallHosts: Int) { 

    } 
} 

,但我得到的錯誤:

Argument passed to call that takes no arguments

任何想法如何實現initWithDelegate功能,我不得不在Objective-C?

+0

你能解釋爲什麼downvote? – BlackM

回答

1

MLANScanner不採取delegate參數其init方法(delegate屬性的MLANScanner)。

您的presenter屬性的定義也存在問題,因爲self在創建時MainVC時無效。

而是執行此操作:

let presenter = MLANScanner() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    presenter.delegate = self 
} 

基於編輯質疑:

var presenter: MLANScanner! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    presenter = MLANScanner(delegate: self) 
} 

注:我的編輯答案假設有一個斯威夫特橋的地方,暴露了一個init(delegate:)方法。有可能沒有,超出了這個問題的範圍。由於代理不是私有的或只讀的,您幾乎可以肯定使用我發佈的第一個版本。

+0

我試過了,但是根本沒有調用initWithDelegate。 – BlackM

+0

MMLANScanner在其方法中接受委託。我意外刪除了。請檢查更新問題。 (對不起) – BlackM

+0

你可能不需要調用'initWithDelegate'我發佈的答案會做你想做的,但看到我的更新可能的替代品。 – par