我是Swift3编程的新手,已经接管并试图重构Swift 2.2到Swift 3中的现有应用程序。我发现Alamofire
有一个新库AlamofireImage
。重构AlamofireImage in Swift 3
在那个库中,我看到有一个imageCache,并且正在考虑是否应该重构当前的imageCache代码以使用它。我的问题是它是否比目前的实施具有主要的优势或效率,如果是的话,它们是什么?任何其他改进此代码的建议也会受到赞赏。
let imageCache = AutoPurgingImageCache()
似乎是一个更简单和可读的实现。
这是当前的imageCache。
class ShoppingManager {
static let sharedManager = ShoppingManager()
let imageCache = NSCache<AnyObject, AnyObject>()
这是原始的Swift 2代码来加载图像和缓存它。
func collectionView(_ collectionView: UICollectionView, cellForItemAtIndexPath indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ProductsCollectionViewCell
// Configure the cell
cell.lblProduct.text = ""
cell.backgroundColor = UIColor.white
cell.imgProduct.image = nil
//load Cell Image
let shopItem = shopItems[indexPath.row]
cell.alamoFireRequest?.cancel()
if let image = ShoppingManager.sharedManager.imageCache.object(forKey: shopItem.imgUrl! as AnyObject) as? UIImage {
cell.imgProduct.image = image
} else {
cell.alamoFireRequest = Alamofire.request(.GET, shopItem.imgUrl!).response(completionHandler: { (_, _, data: Data?, error: NSError?) -> Void in
if error == nil && data != nil {
let img = UIImage(data: data!)
cell.imgProduct.image = img
ShoppingManager.sharedManager.imageCache.setObject(img!, forKey: shopItem.imgUrl!)
}
})
}
return cell
}
这是我已经重构到现在的Swift3代码。
func collectionView(_ collectionView: UICollectionView, cellForItemAtIndexPath indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ProductsCollectionViewCell
// Configure the cell
cell.lblProduct.text = ""
cell.backgroundColor = UIColor.white
cell.imgProduct.image = nil
//load Cell Image
let shopItem = shopItems[indexPath.row]
cell.alamoFireRequest?.cancel()
if let image = ShoppingManager.sharedManager.imageCache.object(forKey: shopItem.imgUrl! as AnyObject) as? UIImage {
cell.imgProduct.image = image
} else {
cell.alamoFireRequest = Alamofire.request(shopItem.imgUrl!).responseImage { response in
guard let img = response.result.value else {
// Handle error
return
}
cell.imgProduct.image = img
ShoppingManager.sharedManager.imageCache.setObject(img, forKey: shopItem.imgUrl! as AnyObject)
}
}
return cell
}
是的,谢谢。我明白这很容易。缓存当前实现为NSCache,我想知道是否有很好的理由将缓存更改为AlamofieImage缓存。 – markhorrocks
我发现,或者我们应该遵循Alamofire,它是完全的包装,否则不要使用Alamofire(与AFNetworking类似)。问题在于混合造成复杂性和调试问题。 –