我是 swift 编程的新手,我搜索了很多关于使用 Swift 使用 NSCache 存储图像的信息。
到目前为止,我所做的是使用 JSON 获取id
s 和imageName
s,并且我将数据保存在数组中,并且能够毫无问题地在单元格中显示图像。现在我想缓存图像。这是我写的代码:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as TableViewCell
//cell.imageView
nameID = self.hoge[indexPath.row]["cars"]["carid"].string!
cell.nameLabel.text = nameID
if let imageFileURL = imageCache.objectForKey(self.hoge[indexPath.row]["cars"]["carid"].intValue) as? NSURL {
println("Get image from cache")
} else {
imageName = self.hoge[indexPath.row]["cars"]["pic_name"].string!
// If the image does not exist, we need to download it
var imgURL: NSURL = NSURL(string: "http://192.168.1.35/car/uploads/" + imageName )!
var image:UIImage = UIImage(named: "pen")!
// Download an NSData representation of the image at the URL
let request: NSURLRequest = NSURLRequest(URL: imgURL)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if error == nil {
image = UIImage(data: data)!
cell.viewCell.image = image
}
else {
println("Error: \(error.localizedDescription)")
}
})
}
return cell
}
那么,如何使用缓存存储和检索图像?