I thought I had a good understanding of Objects and mutability in Objective-C but I've noticed something curious with NSArray
.
If I have the following that doesn't work:
NSArray *myArray = [ [[NSUserDefaults standardUserDefaults] arrayForKey:someKey] arrayByAddingObject:myObject ];
"myObject" is never added to "myArray".
However, the following works:
NSArray *someArray = [[NSUse开发者_运维知识库rDefaults standardUserDefaults] arrayForKey:someKey];
NSArray *myArray = [someArray arrayByAddingObject:myObject];
What's the explanation for this? I know that NSArray
is not mutable but since it is during the initial assignment, it should work since either way seems equivalent.
[[NSUserDefaults standardUserDefaults] arrayForKey:someKey]
returns an NSArray
someArray is an NSArray
And so, an NSArray
is derived simply from [NSArray arrayByAddingObject:Object]
Thanks!
EDIT 1
I am simply wanting to store the NSArray
back to NSUserDefaults
:
[[NSUserDefaults standardUserDefaults] setObject:myArray forKey:someKey];
It was never storing it properly, and so when I debugged I saw that "myObject" was never being added when the array was created.
Note: I have only been testing with [[NSUserDefaults standardUserDefaults] arrayForKey:someKey]
returning a empty/nil
array
EDIT 2
I've isolated the issue a bit; this only happens if [NSUserDefaults standardUserDefaults] arrayForKey:someKey]
returns "nil" (basically, the array doesn't exist in NSUserDefaults
).
I'm still curious to know though why it's not an issue for the 2nd code solution I have.
How are you checking to see if myObject
is ever added? Both code examples look fine, and I've certainly used the former with no issues. But all of your assumptions are correct. The issue, if indeed there is one, lies elsewhere.
That should be the expected behaviour
If you call a method on nil
in Objective-C, you always get nil (or NO/0) as your return value
In this case, when calling NSArray *myArray = [ [[NSUserDefaults standardUserDefaults] arrayForKey:someKey] arrayByAddingObject:myObject ];
, if someKey
isn't set in NSUserDefaults
, then you're calling [nil arrayByAddingObject:]
and so would expect to get nil
back
精彩评论