Reputation: 1647
i've tried to store a couple of strings in my NSUserDefaults... can't figure out what i'm doing wrong...
-(IBAction)addToFavorite:(id)sender {
NSMutableArray* favoritedAlready = [[[NSUserDefaults standardUserDefaults] objectForKey:@"favorites"] mutableCopy];
NSLog(@"%@",favoritedAlready);
if (![favoritedAlready containsObject:indexPathRowString]) {
[favoritedAlready addObject:indexPathRowString];
[[NSUserDefaults standardUserDefaults] setObject:favoritedAlready forKey:@"favorites"];
[[NSUserDefaults standardUserDefaults] synchronize];
favoritMarkerad.image = [UIImage imageNamed:@"StarFilled.png"];}
else {
[favoritedAlready removeObject:indexPathRowString];
[[NSUserDefaults standardUserDefaults] setObject:favoritedAlready forKey:@"favorites"];
[[NSUserDefaults standardUserDefaults] synchronize];
favoritMarkerad.image = [UIImage imageNamed:@"StarEmpty.png"];
}
when I try to load my array in another viewcontroller nothing happens..
(.h)
NSMutableArray *favorites_;
@property (nonatomic, retain) NSMutableArray *favorites_;
(.m)
@synthesize favorites_;
-(void)makeData{
NSMutableArray* favoritedAlready = [[NSUserDefaults standardUserDefaults] objectForKey:@"favorites"];
[[NSUserDefaults standardUserDefaults] synchronize];
favorites_ = favoritedAlready;}
"NSLog(@"%@",favoritedAlready);" gives "2012-01-25 14:53:26.360 myApp[2752:1be03] (null)" any ideas?
Upvotes: 0
Views: 428
Reputation: 4546
The NSMutableArray is (null) at the first point, so you could do this:
if (favoritedAlready == nil) {
favoritedAlready = [[NSMutableArray alloc] init];
}
right after the mutableCopy
method.
So you'll be adding values to the NSMutableArray
instead of adding it to a (null) object
Just like what Tommy said
Upvotes: 1
Reputation: 100632
Based on your comment, the problem is that there is no array in your NSUserDefaults
named 'favorites' at any point. Probably you want to create one if it doesn't exist. So:
-(IBAction)addToFavorite:(id)sender {
// get a mutable copy of the stored array, if there is one
NSMutableArray* favoritedAlready = [[[NSUserDefaults standardUserDefaults]
objectForKey:@"favorites"] mutableCopy];
// if there wasn't a stored array then go ahead and create one to store
if(!favoritedAlready)
favoritedAlready = [NSMutableArray array];
/* ... rest of stuff here ... */
if (![favoritedAlready ...
Upvotes: 2