在尝试使用Swift构建内容时遇到了以下问题。显然,我添加到数组中的值不会通过某些点保存。在任务运行时,它们会随协议一起发送,但在完成后,如果我尝试查看数组中的值,它将返回空。
我做错了什么?我的猜测是在任务完成后它会被释放。如果是这样,有没有办法让它变得强大?我应该知道关于这个任务的事吗?你能告诉我这是如何工作的以及我该怎么办?
以下是代码:
var exchangeArray : ExchangeValues[] = [];
func fetchResult(){
var currenciesOrder = ["EUR", "USD", "GBP", "CHF", "NOK", "SEK", "DKK", "CZK","TRY", "BGN", "MDL", "PLN", "XDR", "XAU", "UAH", "RUB", "RSD","CAD", "AUD", "JPY", "EGP", "BRL","HUF", "MXN","KRW", "CNY","NZD","INR","AED", "ZAR"];
let dateFormat = NSDateFormatter();
dateFormat.dateFormat = "yyyy-MM-dd";
for days in 0..2 {
let daysToSubstract = Double(60*60*24*days);
let date : String = dateFormat.stringFromDate(NSDate().dateByAddingTimeInterval(-daysToSubstract));
var url: NSURL = NSURL(string: "http://openapi.ro/api/exchange/all.json?date=" + date);
var session = NSURLSession.sharedSession();
var task = session.dataTaskWithURL(url, completionHandler: {
(data, response, error) -> Void in
if (response != nil){
var err: NSError?;
if(err?) {
println("request Error \(err!.localizedDescription)");
}
//send the result to protocol
let results = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary;
let temp : NSDictionary = results["rate"] as NSDictionary;
for key in 0..currenciesOrder.count{
for (currencyKey : AnyObject, currencyValue : AnyObject) in temp {
if currenciesOrder[key] as String == currencyKey as String {
let tempExchange = ExchangeValues(currency: currencyKey as? String, value: currencyValue.doubleValue, date:date );
self.exchangeArray.append(tempExchange);
}
}
}
self.delegate?.didReceiveResults(self.exchangeArray);
} else {
println("error: \(error.localizedDescription)");
}
})
task.resume();
}
println("\(exchangeArray.count)");
}
答案 0 :(得分:0)
我有点弄清楚问题是什么:
任务块返回void,所以我认为它在完成后清空了数组。结果是创建另一个从任务调用的函数,其中数组工作得很好(它在存在时传递值),并且可以在那里进行任何进一步的处理。
我希望这有助于某人。代码就像这样简单:
func sendResults(array : ExchangeValues[]) -> Void{
println("\(exchangeArray.count)"); }
当然,如果需要,你可以让函数返回一些东西。