您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

Swift 中的代理與單例模式實現

編輯:iOS 開發綜合

代理與單例是 iOS 開發中最基礎、最常用的兩種設計模式。下面用 Swift 演示它們的典型寫法。

代理(Delegate)

先定義一個代理協議,聲明需要回調的方法;再由持有者通過 weak 引用調用代理方法,避免循環引用。

 protocol FallingObjectDatasourceDelegate:class{ func didCollisionWithTheBallBundary(sender:FallingObjectDatasource , numberOfDisappearedBalls:Int) func didCollisionWithTheBottomBundary(sender:FallingObjectDatasource) } class FallingObjectDatasource: NSObject{ //申明delegate public weak var delegate:FallingObjectDatasourceDelegate? func collisionBehavior(_ behavior: UICollisionBehavior, endedContactFor item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?){ if(identifier != nil) , identifier as! String == PathNames.ballBundaryName{ self.delegate?.didCollisionWithTheBallBundary(sender: self, numberOfDisappearedBalls: self.totalDrops - self.drops.count) }else if identifier as? String == PathNames.referenceBundayName{ self.delegate?.didCollisionWithTheBottomBundary(sender: self) } } }

接下來,只需在需要使用代理的類中實現協議方法即可。

單例(Singleton)

利用 Swift 的私有全局常量配合 dispatch_once 語義,可以實現線程安全的單例:

 private let shareInstance = GameEngine() class GameEngine: NSObject,FallingObjectDatasourceDelegate { class var share: GameEngine { return shareInstance } }

使用時直接調用 GameEngine.share.方法名 即可。這種寫法簡潔直觀,也是 Swift 中實現單例的推薦做法。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved