NSArray mutability and arrayByAddingObject

我怕爱的太早我们不能终老 提交于 2019-12-23 19:55:36

问题


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 = [[NSUserDefaults 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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/5737415/nsarray-mutability-and-arraybyaddingobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!