在混合语言项目中设置Delegate

时间:2014-12-10 11:00:23

标签: objective-c xcode swift integration

我有一个XCode6混合语言项目,结合了Swift和Objective C。

我创建了一个基于Swift的SingleView应用程序,然后添加了2个Objective-C文件,其内容如下:

Singleton.h

#import <Foundation/Foundation.h>

@protocol SingletonDelegate <NSObject>
@optional
- (void)methodCalled;
@end

@interface Singleton : NSObject

@property (weak, nonatomic) id <SingletonDelegate> singletonDelegate;

+ (id)sharedSingleton;

- (void)method;

@end

Singleton.m

#import "Singleton.h"

static Singleton *shared = nil;

@implementation Singleton

- (id)init {
    self = [super init];
    if (self) {

    }
    return self;
}

#pragma mark - Interface

+ (Singleton *)sharedSingleton {
    static dispatch_once_t pred;

    dispatch_once(&pred, ^{
        shared = [[Singleton alloc] init];
    });

    return shared;
}

- (void)method {
    [self.singletonDelegate methodCalled];
}

@end

在设置了XCode建议的桥接头文件后,我在其中添加了#import "Singleton.h"

ViewController.swift中,我尝试设置singletonDelegate但始终失败:

import UIKit

class ViewController: UIViewController, SingletonDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        Singleton.sharedSingleton().singletonDelegate = self // FAILED HERE!!!
        Singleton.sharedSingleton().method()
    }

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


}

错误消息是:

  

无法分配此表达式的结果

有人能告诉我如何解决这个问题吗? (我是将Objective-C集成到Swift项目中的新手)

提前致谢,

1 个答案:

答案 0 :(得分:1)

创建一个类变量。然后设置其代理。

let singleton: Singleton = Singleton.sharedSingleton()

override func viewDidLoad() {
       super.viewDidLoad()
       // Do any additional setup after loading the view, typically from a nib.

       singleton.singletonDelegate = self
       //Singleton.sharedSingleton().singletonDelegate = self // FAILED HERE!!!
       //Singleton.sharedSingleton().method()
   }

fun methodCalled() {
   //This method gets called from the Singleton class through the delegate
}