将NSData objectiveC代码转换为swift时出错

时间:2015-01-14 08:37:50

标签: objective-c swift nsstring nsdata

我尝试将Objective C中的代码转换为Swift,

- (IBAction) sendMessage {

    NSString *response  = [NSString stringWithFormat:@"msg:%@", inputMessageField.text];
    NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
    [outputStream write:[data bytes] maxLength:[data length]];
    inputMessageField.text = @"";

}
下面是我的快捷代码。

@IBAction func sendMessage() {

        var response  = NSString.localizedStringWithFormat("msg:\(inputMessageField?.text)")
        var data = NSData(Data :response , dataUsingEncoding:NSASCIIStringEncoding)
        outputStream(write:data.bytes, maxLength:data.length);
        inputMessageField?.text = ""

    }

我收到错误,告知数据是一个额外的参数。请帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

没有NSData(Data :response , dataUsingEncoding:NSASCIIStringEncoding)方法。你可能正在寻找

let data = 
response.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

您的整个代码应如下所示:

let response  = NSString.localizedStringWithFormat("msg:\(inputMessageField?.text)")
if let data = response.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
    outputStream(write:data.bytes, maxLength:data.length);
    inputMessageField?.text = ""
}
else {
    println("could not convert response \"\(response)\" to NSData")
}

尽可能使用let,并检查可用的初始值是否返回值

答案 1 :(得分:0)

您正在寻找NSData(Data :response , dataUsingEncoding:NSASCIIStringEncoding)的方法不存在。

你可以像这样转换

var data = NSData(data :response.dataUsingEncoding(NSASCIIStringEncoding)!)


<强>已更新

方法outputStream.write()需要UInt8[]数组,因此您必须将数据转换为UInt8[] Array

你的代码应该是,

@IBAction func sendMessage() {
    var response  = NSString.localizedStringWithFormat("msg:\(inputMessageField?.text)")
    var data = NSData(Data :response , dataUsingEncoding:NSASCIIStringEncoding)        
    outputStream.write(UnsafePointer(data.bytes), maxLength:data.length)
    inputMessageField?.text = ""
}