2015-05-03 47 views
-2

我正在使用Swift metawear(mbientlab.com)项目,并且所有代码示例都在Objective C中,因此必须进行大量转换。根据这一博客帖子 - http://projects.mbientlab.com/persistent-events-and-filters/ - 我创建了下面的类,从MBLRestorable(它实现NSCoder协议)继承:将目标C alloc init转换为需要参数的swift

class DeviceConfiguration:NSObject, MBLRestorable { 
var pulseWithEvent:MBLEvent! 

func encodeWithCoder(aCoder: NSCoder) { 
    aCoder.encodeObject(self.pulseWithEvent, forKey: "pulseWithEvent") 
} 

required init(coder aDecoder: NSCoder) { 
    super.init() 

    self.pulseWithEvent = aDecoder.decodeObjectForKey("pulseWithEvent") as MBLEvent 
} 
} 

到目前为止好。现在我下面的目标C转换为斯威夫特:

[self.device setConfiguration:[[DeviceConfiguration alloc] init] handler:^(NSError *error) { 
if (!error) { 
// Programming successful! 
} 
}]; 

我尝试:

self.device.setConfiguration(MetawearConfig()) { error in 

}

但得到一个错误,它缺少必需的参数“编码器”。对我来说,它需要初始化参数,但在Objective C示例代码/应用程序中,编码器obj永远不会传入(并且编译器不会引发相同的错误)。

的声明setConfiguration是:

- (void)setConfiguration:(id<MBLRestorable>)configuration handler:(MBLErrorHandler)handler; 

什么我失踪?

+0

你可以显示'self.device.setConfiguration'的签名 –

+0

我刚刚添加了签名。 –

回答

0

斯威夫特类默认情况下不会继承父类的初始化(见斯威夫特语言指南 - >初始化 - >搜索部分“自动初始化程序继承”) 。 NSObjectinit()是“指定初始值设定项”。如果子类实现其自己的指定初始值设定项,则指定的初始值设定项仅由子类继承。由于DeviceConfiguration类实现了指定的初始化程序init(coder:),因此它不会从其超类继承指定的初始化程序。这就是为什么DeviceConfiguration没有签名init()的初始化程序。

Objective-C的不同之处在于初始值设定项只是Objective-C中的方法,并且总是被继承。

0

Objective-C中的DeviceConfiguration也将有不同的init,没有参数,从NSObject继承。您正在转换的代码看起来是调用无参数版本,而不是NSCoder版本。

+0

你是说在Objective-C中它会继承它不会在Swift中的非参数init方法吗? –

1

您在致电MetawearConfig(),但您提供的唯一initinit(coder aDecoder: NSCoder)。如果你想要一个无参数init,你必须提供一个:

init() { 
    // initialize your object 
} 
+0

但是你可以在http://projects.mbientlab.com/persistent-events-and-filters/看到的Objective-C版本没有提供。 –

+1

Swift和ObjC是不同的语言,并有不同的对象初始化规则。请注意,一般来说,基本语言翻译问题对于StackOverflow而言是无关紧要的。 http://meta.stackoverflow.com/questions/265825/code-translation-tagging –