evgenyneu / keychain-swift

Helper functions for saving text in Keychain securely for iOS, OS X, tvOS and watchOS.
MIT License
2.82k stars 345 forks source link

KeychainSwift intended to be used as a singleton? #139

Open thisisjeffwong opened 3 years ago

thisisjeffwong commented 3 years ago

I notice in each example in the main readme that a new KeychainSwift() is instantiated before use. This could be interpreted to mean each use of the keychain should instantiate a KeychainSwift object before use.

However, I notice there is a private NSLock in each instance and the lock is acquired before getting or setting. This would imply that there should only be one instance accessed in your app. Otherwise, the locks are meaningless since they are not a single lock across all instances.

Is it a mistake to instantiate one of these at each get and set?

evgenyneu commented 3 years ago

@thisisjeffwong very good point, if you access Keychain from different threads, then it's better to use single instance

let keychain = KeychainSwift()
...
keychain.set("Hello world", forKey: "my key")

instead of

KeychainSwift().set("Hello world", forKey: "my key")

I've removed the KeychainSwift().set() example the readme. Well-spotted. 👍