Sergey Grishchev
Sergey Grishchev

Reputation: 12051

Adding NSString to NSMutableArray substitutes the previous NSString

I'm basically trying to add a new string to my NSMutableArray using this code in ViewWillAppear

    NSUserDefaults *favBooksDefaults = [NSUserDefaults standardUserDefaults];
    self.favBook = [favBooksDefaults stringForKey:@"favBook"];
    self.favBookList = [[NSMutableArray alloc]init];
    [self.favBookList addObject:favBook];

Of course, while I do this, I want to preserve ALL the previous strings that were present in the Array. Because when I add a new string for the NSUserDefaults and then to the Array, it simply substitutes the old one.

Why is that and how can I save all the objects? Thanks in advance.

Upvotes: 1

Views: 1973

Answers (4)

tia
tia

Reputation: 9698

NSUserDefaults *favBooksDefaults = [NSUserDefaults standardUserDefaults];
self.favBook = [favBooksDefaults stringForKey:@"favBook"];
if ([self.favBookList indexOfObject:self.favBook] != NSNotFound) {
    [self.favBookList addObject:favBook];
}

You should also init your favBookList in viewDidLoad method:

self.favBookList = [NSMutableArray array];

Upvotes: 1

Matt Meyers
Matt Meyers

Reputation: 143

Mr Br.'s answer is correct:

In your header file declare favBookList as a property and include a book adding method:

@interface yourViewController : UIViewController {
NSMutableArray *favBookList;
}

-(void)addBook;

@property (nonatomic, retain) NSMutableArray *favBookList;

In your viewDidLoad method, initialize favBookList. Don't forget @synthesize!

-(void)viewDidLoad {
self.favBookList = [[NSMutableArray alloc] init];
[super viewDidLoad];
}

Now you are free to add a book from your user defaults at any time.

-(void)addBook{
self.favBook = [[NSUserDefaults standardUserDefaults] stringForKey:@"favBook"];
[favBookList addObject:favBook]; 
}

Upvotes: 1

h4cky
h4cky

Reputation: 894

NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:oldArray];
[newArray replaceObjectAtIndex:oldObjectIndex withObject:newObject] // if you want to replace oldObject with newObject;
[newArray addObject:newObject] // if you want to add object to the array;

If i get it right you want to replace the old object with new one?

Upvotes: 1

MrBr
MrBr

Reputation: 1916

When you alloc and init a new NSMutableArray object you will have an empty array with no values in it. It doesn't substitute it as there is nothing to substitute in there. It just adds the NSSString as the first value. This of course happens EVERY time you alloc/init a new instance of NSMutableArray.

SOLUTION: Make the NSMutableArray a instance variable of your view controller. alloc/init it once (e.g. in the viewDidLoad). Every time viewWillAppear gets called you can add values without reinitializing a new NSMutableArray.

Upvotes: 1

Related Questions