我有一個自定義的委託/協議設置。我使用alamofire來獲取請求,然後解析json。 json被安排到Swift對象中,並傳遞迴集合視圖控制器。除了將它們發回的委託從未被調用。其他的一切都很完美。這裏是我的相關代碼:代表不叫
class ViewController: UICollectionViewController, MainCatGallery {
var cats = [Cats]()
let theManager = ImgurAPIManager()
override func viewDidLoad() {
super.viewDidLoad()
loadCats()
theManager.delegate = self
}
func gotCatsArray(x: [Cats]) {
self.cats = x
self.collectionView?.reloadData()
}
}
和:
protocol MainCatGallery {
func gotCatsArray(x: [Cats])
}
class ImgurAPIManager: NSObject {
static let sharedInstance = ImgurAPIManager()
let jsonClass = ParseJson()
var delegate:MainCatGallery?
var catGallery = [Cats]()
func getGallery() {
Alamofire.request(Router.Get)
.response { (request, response, data, error) -> Void in
do {
let jsonDict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
self.catGallery = self.jsonClass.parseCatGalleryJson(jsonDict)
for x in self.catGallery {
print(x.url!)
}
self.delegate?.gotCatsArray(self.catGallery)
}
catch {
}
}
}
}
所有這一切工作正常 - 預期print語句在getGallery()函數打印出每個URL。就在它調用委託時,它永遠不會將對象傳遞迴視圖控制器。並且設置斷點表明它永遠不會傳回數據。
我在代表/協議的其他項目中使用過這個完全相同的模式,並且從來沒有遇到過問題。任何想法爲什麼它沒有被召喚?
何時何地你叫'getGallery'?調用'loadCats()'時它是否被視圖控制器調用? –
您正在創建ImgurAPIManager的新實例並將其委託給它。請使用您的sharedInstance設置委託或使您的委託保持靜態。 –
@Roman yes loadCats()調用get gallery方法,但DanBeaulieu已經正確回答。 ImgurAPIManager.sharedInstance.delegate = self是正確的。把它放在答案中,我會接受它。 – joey