Reputation: 246
I want to store data in key value pair in NSMutableDictionary
and Store that dictionary in NSArray
on everytime the button clicks.
Problem - New data replaces the old one in that array
Code -
- (void)viewDidLoad {
[super viewDidLoad];
_filledDict = [[NSMutableDictionary alloc] init];
_addedArray = [[NSMutableArray alloc] init];
}
- (IBAction)addMoreClicked:(UIButton *)sender {
NSString *availableTo = [to stringByReplacingOccurrencesOfString:@"" withString:@""];
NSString *from = [[_tfDateFrom.text stringByAppendingString:@" "] stringByAppendingString:_tfTimeFrom.text];
[_filledDict setObject:availableFrom forKey:@"fromDate"];
[_filledDict setObject:availableTo forKey:@"toDate"];
[_addedArray addObject:_filledDict];
_tfDateFrom.text = @"";
_tfDateTo.text = @"";
_tfTimeFrom.text = @"";
_tfTimeTo.text = @"";
}
Result I am getting -
<__NSArrayM 0x60000045d6d0>(
{
fromDate = "2018-08-10 11:16:37";
toDate = "2018-08-10 11:16:39";
},
{
fromDate = "2018-08-10 11:16:37";
toDate = "2018-08-10 11:16:39";
}
)
Upvotes: 1
Views: 41
Reputation: 1701
You are not initializing dicionary every time so it happens. Please find the below code.
- (IBAction)addMoreClicked:(UIButton *)sender {
NSString *availableTo = [to stringByReplacingOccurrencesOfString:@"" withString:@""];
NSString *from = [[_tfDateFrom.text stringByAppendingString:@" "] stringByAppendingString:_tfTimeFrom.text];
_filledDict = [[NSMutableDictionary alloc] init];
[_filledDict setObject:availableFrom forKey:@"fromDate"];
[_filledDict setObject:availableTo forKey:@"toDate"];
[_addedArray addObject:_filledDict];
_tfDateFrom.text = @"";
_tfDateTo.text = @"";
_tfTimeFrom.text = @"";
_tfTimeTo.text = @"";
}
Upvotes: 0
Reputation: 3007
Because of NSMutableDictionary
and NSMutableArray
is reference type, so when you update the data of _filledDict
, it will update in the object, that you added to NSMutableArray
too.
You can simple change _filledDict
to the function's scope variable to fix it
- (void)viewDidLoad {
[super viewDidLoad];
// Remove it
// _filledDict = [[NSMutableDictionary alloc] init];
_addedArray = [[NSMutableArray alloc] init];
}
- (IBAction)addMoreClicked:(UIButton *)sender {
// Change to
NSMutableDictionary *filledDict = [[NSMutableDictionary alloc] init];
[filledDict setObject:availableFrom forKey:@"fromDate"];
[filledDict setObject:availableTo forKey:@"toDate"];
[_addedArray addObject:filledDict];
}
Upvotes: 1