Saya mencoba untuk memeriksa apakah default pengguna ada, terlihat di bawah ini:
func userAlreadyExist() -> Bool {
var userDefaults : NSUserDefaults = NSUserDefaults.standardUserDefaults()
if userDefaults.objectForKey(kUSERID) {
return true
}
return false
}
Namun, tidak peduli apa itu akan selalu kembali benar bahkan ketika objek tersebut belum ada? Apakah ini cara yang tepat untuk memeriksa keberadaan?
ios
swift
nsuserdefaults
Ryan
sumber
sumber
Ya ini adalah cara yang tepat untuk memeriksa
optional
memilikinil
atau nilai apapunobjectForKey
kembali metodeAnyObject?
yangImplicit optional
.Jadi jika
userDefaults.objectForKey(kUSERID)
memiliki nilai apa pun daripada yang dievaluasitrue
. jikauserDefaults.objectForKey(kUSERID)
memilikinil
nilai daripada yang dievaluasifalse
.Dari panduan pemrograman cepat
Sekarang ada bug di simulator daripada setelah kunci pengaturan di
userDefaults
mereka selalu tetap disetel tidak peduli Anda menghapus aplikasi Anda. Anda perlu mengatur ulang simulator.Reset your Simulator check this method before setting key in
userDefaults
or remove keyuserDefaults.removeObjectForKey(kUSERID)
fromuserDefaults
and it will returnNO
.On devices it is resolved iniOS8 beta4
.sumber
objectForKey
method returnsAnyObject!
which is Implicit optional " This is wrong it returnsAnyObject?
if anOptional { }
and it will suggest you test using == nil or != nilThis is essentially the same as suggested in other answers but in a more convenient way (Swift 3+):
extension UserDefaults { static func contains(_ key: String) -> Bool { return UserDefaults.standard.object(forKey: key) != nil } }
usage:
if UserDefaults.contains(kUSERID) { ... }
sumber
static func contains(key: String) -> Bool
. Otherwise, makes more sense to makereturn self.object(forKey: key) != nil
Simple Code to check whether value stored in UserDefault.
let userdefaults = UserDefaults.standard if let savedValue = userdefaults.string(forKey: "key"){ print("Here you will get saved value") } else { print("No value in Userdefault,Either you can save value here or perform other operation") userdefaults.set("Here you can save value", forKey: "key") }
sumber
for swift 3.2
func userAlreadyExist(kUsernameKey: String) -> Bool { return UserDefaults.standard.object(forKey: kUsernameKey) != nil }
sumber
public class PreferencesUtils { private init() { } public static func setBoolData(boolValue: Bool, dataName: String) { UserDefaults.standard.set(boolValue, forKey: dataName) } public static func getBoolData(dataName: String)-> Bool{ let defaults = UserDefaults.standard if(defaults.value(forKey: dataName) != nil) { return defaults.value(forKey: dataName)! as! Bool } else { return false } } public static func saveStringData(data: String, dataName: String){ let preferences = UserDefaults.standard preferences.set(data, forKey: dataName) let didSave = preferences.synchronize() if !didSave { debugPrint("Not saved yet") } } public static func getSavedStringData(dataName: String)-> String{ let defaults = UserDefaults.standard if(defaults.value(forKey: dataName) != nil){ return defaults.value(forKey: dataName) as! String } else { return "" } } public static func saveIntData(data : Int, dataName: String){ let preferences = UserDefaults.standard preferences.set(data, forKey: dataName) let didSave = preferences.synchronize() if !didSave { debugPrint("Not saved yet") } } public static func getSavedIntData(dataName: String) -> Int { let defaults = UserDefaults.standard if(defaults.value(forKey: dataName) != nil){ return defaults.value(forKey: dataName) as! Int }else{ return 0 } } }
Or you can try this library: Link
sumber
func keyExists(key: String) -> Bool { guard let _ = UserDefaults.standard.object(forKey: key) { return false; } return true; }
sumber
override func viewDidLoad () {
super.viewDidLoad ()
jika UserDefaults.standard.string (forKey: "CHARRY") == "CHARRY" {
lb.text = "CHARRY" im.image = UIImage(named: "CHARRY")
}}
@IBAction func PressedCar(_ sender: UIButton){ lb.text = "CHARRY" im.image = UIImage(named: "CHARRY") UserDefaults.standard.set("CAR", forKey: "CHARRY") }
sumber
Banyak solusi di sini yang valid. Tetap saja, saya pikir mereka menyelesaikan masalah yang salah.
Biasanya, kode seperti ini digunakan untuk memeriksa apakah suatu nilai ditetapkan sehingga nilai default lain dapat digunakan:
if isKeyPresentInUserDefaults(key: "username") { return UserDefaults.standard.string(forKey: "username") } else { return "No username was set" }
You shouldn't care if a key is set or not. There is a far more elegant approach for having default values in
UserDefaults
:UserDefault.standard.register(defaults: ["username": "No username was set"])
If you run this code at app launch, subsequent calls to
UserDefaults.standard.string(forKey: "username")
will return the default value of"No username was set"
if no value was set for the key yet.sumber