【发布时间】:2016-07-02 01:14:09
【问题描述】:
在我的viewDidLoad 我愿意:
// Get Profile Info
NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in
let getMyProfileURL = "\(self.property.host)\(self.property.getMyProfile)"
print(getMyProfileURL)
Alamofire.request(.POST, getMyProfileURL, parameters: self.property.profileParameteres, encoding: .JSON).responseJSON { response in
do {
let json = JSON(data: response.data!)
if json["user"].count > 0 {
self.profileDetails.append(ProfileDetailsModel(json: json["user"]))
}
}
}
print(self.profileDetails[0].firstName)
}
所以,当我想从数组中获取firstName 时:
print(self.profileDetails[0].firstName)
我的应用程序因错误而崩溃:
fatal error: Array index out of range
我的数组是空的。我已经使用了NSOperationQueue,但我仍然得到空数组并崩溃。如何解决此问题并从控制器中的任何位置访问我的 filled 数组,而不仅仅是在 Alamofire 块内?
【问题讨论】:
-
如果数组为空,可能意味着您没有从服务器获得任何响应。或者您访问 json 的密钥错误。
-
另外,您的 json 本身可能会作为数组返回,因此请尝试使用
json[0]["user"]之类的方法来访问第一个等。 -
试试
print(json)看看你正在使用什么样的数据结构。 -
@Phoen1xUK 我知道我有什么数据。那不是我的问题。我的问题是从我的控制器中的其他地方访问它
-
啊,是的,在重新阅读您的代码并查看其他答案之后,我可以看到您正在尝试在请求完成之前访问数组,因为 Alamofire 请求将是异步的,并且打印将立即执行。
标签: ios swift asynchronous alamofire nsoperationqueue