Jtaylorapps
Jtaylorapps

Reputation: 5780

Add NSArray To NSMutableArray

Thanks for you time and reading this. What I'm trying to do is figure out why this NSLog is telling me the NSArray is always null, no matter what. I'm thinking that the problem is that I'm initiating the NSMutableArray wrong. 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?

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

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];
}

Upvotes: 0

Views: 6592

Answers (2)

jroyce
jroyce

Reputation: 2148

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

myNSMutableArray = [NSMutableArray arrayWithArray:myArray];

Upvotes: 6

UIAdam
UIAdam

Reputation: 5313

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

Upvotes: 0

Related Questions