Skip to content

A small swift helper class for using an ObjectPool

License

Notifications You must be signed in to change notification settings

e-sites/ObjectPool

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ObjectPool

A small swift helper class for using an ObjectPool

forthebadge forthebadge

Compatible with:

  • Swift 4
  • Xcode 9
  • Cocoapods 1.3

Usage

Init

class SomeView: UIView, ObjectPoolInstance {
    required convenience init() {
        self.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100)
    }
}

var objectPool: ObjectPool<SomeView>!

override func viewDidLoad() {
   super.viewDidLoad()
    
   objectPool = ObjectPool<SomeView>(size: 20, policy: .dynamic) { obj in
       obj.backgroundColor = UIColor.red
   }
   
   objectPool.onAcquire { [weak self] obj in 
       DispatchQueue.main.async {
           self?.view.addSubview(obj)
       }
   }
   
   objectPool.onRelease { obj in 
       DispatchQueue.main.async {
           // It's safe to remove the object from its superview,
           // since `ObjectPool` will keep its (memory) retained.
           obj.removeFromSuperview()
      }
   }
}

Get an object from the pool:

do {
    let object = try objectPool.acquire()
    object.backgroundColor = UIColor.orange
} catch let error {
    print("Error acquiring object: \(error)")
}

Done using the object:

objectPool.release(object)

Policies

  • dynamic: If the pool is drained, fill up the pool with +1
  • static : The pool size is fixed. If the pool is drained, throw Error.drained

Installation

Podfile

pod 'ObjectPool', :git => 'https://github.com/e-sites/ObjectPool.git'

About

A small swift helper class for using an ObjectPool

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published