I have two view controllers. The first one has a segue to another view controller. What I want for the latter view controller is to add items coming from a text field then save it in an array through a button click. Then this array will be saved using NSUserDefaults.
On the code below, I can store items in my array successfully. This array is also saved using NSUserDefaults. Yet, when I get back to my first view controller, and then proceed again to my 2nd view controller to add new items on my array, the items I stored earlier were gone. The newly added items were the only ones saved.
Advice please :)
in my .h file
@interface AddCardViewController : UIViewController <UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITextField *cardNameTextField;
@end
in my .m file
@interface AddCardViewController ()
@property (nonatomic, strong)NSMutableArray *nameOfCards;
@end
@implementation AddCardViewController
@synthesize cardNameTextField = _cardNameTextField;
@synthesize nameOfCards = _nameOfCards;
// setting my array
- (NSMutableArray *)nameOfCards
{
if (!_nameOfCards) _nameOfCards = [[NSMutableArray alloc] init];
return _nameOfCards;
}
- (void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
self.cardNameTextField.delegate = self;
}
- (BOOL) textFieldShouldReturn:(UITextField *)textField{
[self.cardNameTextField resignFirstResponder];
return YES;
}
- (void)viewDidLoad
{
//getting the data saved
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *cardName = [defaults objectForKey:@"cardName"];
NSLog(@"contents of my array %@", cardName);
[super viewDidLoad];
}
- (IBAction)addNewCard:(id)sender {
[self.nameOfCards addObject:self.cardNameTextField.text];
NSLog(@"contents :%@", _nameOfCards);
// this is how to save the data
NSMutableArray *cardName = _nameOfCards;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:cardName forKey:@"cardName"];
[defaults synchronize];
NSLog(@"data saved");
}
@end