-3

My App crashing due to Empty or null value from NSUserDefaults. How to validate NSUSerdefaults Having value or not?

let empName = NSUserDefaults.standardUserDefaults().stringForKey("EMP_NAME")

        lblUserName.text = "Hello I'm \(empName!)"
  • 1
    By not using the crash operator `!`, and instead [dealing with the optional values properly](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu)? – Hamish May 27 '16 at 15:48
  • If you want help with your issue you should update your question with relevant code. – rmaddy May 27 '16 at 15:52
  • Now i added my code. – Jupit Kumar May 27 '16 at 15:57
  • 2
    @originaluser2 I love the phrase "crash operator". This needs to be an official coined phrase. – Slayter May 27 '16 at 18:59

1 Answers1

2

Check below possible conditions.

1. Check NSUserDefaults is null:

if(NSUserDefaults.standardUserDefaults().objectForKey("EMP_NAME") == nil)
{
   print("NULL")
}

2. Check NSUserDefaults String is null or Empty:

if((NSUserDefaults.standardUserDefaults().stringForKey("EMP_NAME")) == "" || NSUserDefaults.standardUserDefaults().stringForKey("EMP_NAME") == nil)
{
   print("NULL or Empty String")
}
PREMKUMAR
  • 8,283
  • 8
  • 28
  • 51
  • 2
    Why did you delete your first answer and repost it again exactly as it was? That's not the way to get around a down vote. – rmaddy May 27 '16 at 15:59
  • I am trying to edit. But its duplicated so only i removed one answer. @rmaddy – PREMKUMAR May 27 '16 at 16:00
  • @PREMKUMAR You can freely [edit your posts](http://stackoverflow.com/posts/37487828/edit) without having to re-post. – Hamish May 27 '16 at 16:05
  • @originaluser2 oh fine. Now i need to remove this post and unDelete old post and i can edit? – PREMKUMAR May 27 '16 at 16:06
  • @PREMKUMAR Just leave it be, no point in unnecessarily deleting and un-deleting. Just make sure to bear it in mind for the future – it certainly looks incredibly suspicious if you delete a post with a down-vote on it and then re-post it. Also bear in mind that people with 10k+ rep can see deleted posts. – Hamish May 27 '16 at 16:09
  • @originaluser2 Yes i understood. – PREMKUMAR May 27 '16 at 16:10