1.OC中的寫法
在OC中,我們需要保存圖片到相冊需要調(diào)用這個方法:
void UIImageWriteToSavedPhotosAlbum(UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo);
想來大家也都看過這個方法的頭文件容客,在頭文件中有這樣一段話
// Adds a photo to the saved photos album. The optional completionSelector should have the form:
// - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
意思是:想要將一張照片保存到相冊中,這個可選的完成方法需要按照下面那個方法的格式來定義冲粤。
所以陌凳,我們在OC中通常都是直接將這個方法拷貝出來弓乙,直接實現(xiàn)這個方法憨闰,舉個栗子:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UIImageWriteToSavedPhotosAlbum(self.iconView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error) {
NSLog(@"保存出錯");
return;
}
NSLog(@"保存成功");
}
在上面這個栗子中拆宛,我通過手指觸摸事件遇绞,將事先定義好的iconView中的圖像保存到相冊中键袱。
而同樣一個栗子,在Swift中應(yīng)該怎么樣實現(xiàn)呢摹闽?
2.swift中的寫法
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
UIImageWriteToSavedPhotosAlbum(iconView.image, self, "image:didFinishSavingWithError:contextInfo:", nil)
}
func image(image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject) {
println("---")
if didFinishSavingWithError != nil {
println("錯誤")
return
}
println("OK")
}
同樣的栗子蹄咖,swift中的實現(xiàn)如上,在swift中付鹿,我們跳到頭文件會發(fā)現(xiàn)是這樣的澜汤,
// Adds a photo to the saved photos album. The optional completionSelector should have the form:
// - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
還是OC中那一套,蘋果并沒有幫我們寫好swift下的代碼格式應(yīng)該怎么寫舵匾,所以很多人對此應(yīng)該怎么使用會產(chǎn)生許多的疑惑俊抵,其實,就是像上面那樣坐梯,將參數(shù)一一對應(yīng)徽诲,以swift中函數(shù)的寫法寫出來就可以了。
另外補充一點小知識點:
上面的那個方法我們還可以這么寫,
// 提示:參數(shù) 空格 參數(shù)別名: 類型
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
println("---")
// if didFinishSavingWithError != nil {
if error != nil {
println("錯誤")
return
}
println("OK")
}
類似這樣的格式:(參數(shù) 參數(shù)別名: 類型)didFinishSavingWithError error: NSError?
在外部調(diào)用時谎替,顯示的是didFinishSavingWithError這個參數(shù)名
而在內(nèi)部使用時偷溺,顯示的是error這個參數(shù)別名,方便我們的使用钱贯,也更加類似OC中的寫法挫掏。