0

i have a Question: when we access an "objectForKey"and the key doesn't exist, this ll return nil but no error/exception, so the question is that after this statement/line is executed, does the runtime system creates a key with the name specified and set it nil OR although nil is the output but no such key is created????

Muhammad Waqas
  • 904
  • 2
  • 10
  • 21

3 Answers3

1

In a word: No.

NSDictionary is immutable and objectForKey is a method on the NSDictionary class.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • @iOS_Developer No, same answer. – trojanfoe Jul 01 '14 at 07:16
  • No. And you can't put the value nil into an NSDictionary (or any collection class like NSArray or NSSet for that matter). Try it. If you do it explicitly Xcode won't compile your code. If you try to insert a variable with a value of nil you'll get an exception. – Brandon Jul 01 '14 at 07:16
  • @BrandonRoth yes i just got it from someone else, so to store nil [NSNull null] ll return an object with nil value, right??? – Muhammad Waqas Jul 01 '14 at 07:39
  • 2
    @iOS_Developer No, it will return the (singleton) `NSNull` object. – trojanfoe Jul 01 '14 at 07:40
1

No it wont modify the dictionary. If the key does not exist then it simply returns nil value.

To confirm this you can set a breakpoint in Xcode for an invalid key and check if dictionary is modified or not. (And moreover NSDictionary is immutable i.e you cannot add/remove objects)

GoodSp33d
  • 6,252
  • 4
  • 35
  • 67
  • and in case of NSMutableDictionary ll u answer to YES??? If the key does not exist then will it still returns nil value + no creation of that key?? – Muhammad Waqas Jul 01 '14 at 07:15
  • @iOS_Developer Why dont you check it out by debugging ;) – GoodSp33d Jul 01 '14 at 07:17
  • and this nil shows that no such key exists OR there is no value for this key, kindly tell me specifically – Muhammad Waqas Jul 01 '14 at 07:19
  • 1
    @iOS_Developer Nil returned means there is no such key. It cannot mean there is no value associated with this key because NSDictionary cannot hold `nil` value (`[NSNull null]` is allowed). Same holds good for NSArray and Mutable classes as well. If you do insert a nil value it will crash if not handled properly. – GoodSp33d Jul 01 '14 at 07:30
  • and [NSNull null] ll store nil as an object in a key, right?? – Muhammad Waqas Jul 01 '14 at 07:36
  • 1
    They are both different, in a way yes `[NSNull null]` allows you to store NULL value objects. Check out this [question](http://stackoverflow.com/questions/836601/whats-the-difference-between-nsnull-null-and-nil) for more clarity. – GoodSp33d Jul 01 '14 at 07:41
0

You can Log your dictionary after the line executed to see it.

You will see that NSDictionary is immutable, it won't modify your dictionary. ;)

Kevin Machado
  • 4,141
  • 3
  • 29
  • 54