NSArray的!当我使用NSString时,与UInt8不同

时间:2014-10-26 07:42:55

标签: ios swift casting nsarray

我正在构建一个聊天应用程序,在那里我以json格式从服务器获取所有消息。结果是:

{"success":"true","userid":"2","messages":[{"id":"1","senderid":"1","receiverid":"2","message":"Hey there!"},{"id":"2","senderid":"1","receiverid":"2","message":"How are you?"},{"id":"3","senderid":"1","receiverid":"2","message":"Hey "},{"id":"4","senderid":"1","receiverid":"2","message":"Hey"},{"id":"5","senderid":"1","receiverid":"2","message":"Yo!"},{"id":"6","senderid":"1","receiverid":"2","message":"Yo!"},{"id":"7","senderid":"1","receiverid":"2","message":"asd"},{"id":"8","senderid":"2","receiverid":"1","message":"Leave me alone!"}]}

我正在尝试接收每个项目的message,并将其显示在tableview中。

我的表视图当前没有NSArray,但是当它调用getMessages()方法时,我想用所有消息填充数组。

这是我的代码:

var content: AnyObject! = jsonData.valueForKey("messages")
for message in content as [NSDictionary] {
    if let m = message["message"] as? [NSString] {
        listDataArray += m
    }
}

但它会引发错误:

'NSArray!' is not identical to 'UInt8'

就行:

listDataArray += m

任何想法如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

你应该append到数组。+=运算符用于从数组中添加元素

 listDataArray.append(m)

如果是NSArray,请NSMutableArray

  //Change where listDataArray declared
  var listDataArray:NSMutableArray = NSMutableArray()

  //addthe objects
  listDataArray.addObject(m)

答案 1 :(得分:1)

要附加到listDataArray的固定代码是:

if let m = message["message"] as? NSString {
    listDataArray += [m]
}

错误是message["message"]是一个字符串,而不是一个字符串数组。

我不知道您是否尝试使用此代码自动将字符串转换为包含该字符串的数组:

if let m = message["message"] as? [NSString] {

如果是的话,那不起作用......

请注意+=运算符的用法,该运算符将右侧数组的所有元素追加到左侧的数组 - 这就是变量m被包含在内的原因一个数组:[m]


事实证明,listDataArrayNSMutableArray(不是吗?),在这种情况下,添加到数组的代码就是:

if let m = message["message"] as? NSString {
    listDataArray.addObject(m)
}