xcode 将 NSArray 添加到 NSMutableArray

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9561480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 23:31:56  来源:igfitidea点击:

Add NSArray To NSMutableArray

iosxcodensmutablearraynsuserdefaults

提问by JTApps

Thanks for you time and reading this. What I'm trying to do is figure out why this NSLogis telling me the NSArrayis always null, no matter what. I'm thinking that the problem is that I'm initiating the NSMutableArraywrong. Could you perhaps take a look and decide whether or not I did it right, and if at all possible give me a way to pass the array into the NSMutableArray?

感谢您抽出时间阅读本文。我想要做的是弄清楚为什么这NSLog告诉我NSArray不管怎样总是为空。我在想问题在于我开始NSMutableArray错误了。你能不能看看我是否做对了,如果可能的话,给我一种方法来将数组传递到NSMutableArray?

Thanks!

谢谢!

 //Get Defaults
 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
 NSArray *favoriteArray = [[defaults objectForKey:@"favorites"] copy];

//Declares Mutable Array
self.favorites = [[NSMutableArray alloc] initWithObjects:favoriteArray, nil];
NSLog(@"array: %@", favorites);

UPDATE: I figured it out. It turns out you have to declare it with initWithArray rather than trying to add it as an object

更新:我想通了。事实证明,您必须使用 initWithArray 声明它,而不是尝试将其添加为对象

Solution:

解决方案:

- (void)viewDidLoad {

     //Get Defaults
     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
     NSArray *favoriteArray = [[defaults objectForKey:@"favorites"] copy];

    //Declares Mutable Array
    self.favorites = [[NSMutableArray alloc] initWithArray:favoriteArray];

    [super viewDidLoad];
}

回答by jroyce

The way to do this is using the arrayWithArray and here is how you do it:

这样做的方法是使用 arrayWithArray,这里是你如何做到的:

myNSMutableArray = [NSMutableArray arrayWithArray:myArray];

回答by UIAdam

Do you ever set an object in your user defaults for the "favorites" key?

你有没有在你的用户默认设置中为“收藏夹”键设置一个对象?