Reputation: 717
I need to add contents of textfield named productName
to an NSMutableArray
named cartArray
by clicking on a button.
In the button action event I wrote:
NSString *productName = [NSString stringWithFormat:@"%@", productName.text];
cartArray = [[NSMutableArray alloc] init];
[cartArray addObject:productName];
NSLog(@"Cart Array==%@", cartArray);
But i need to add that content of textfield each time user click on button. Here in console previous content in array not showing i.e. it's not get added each time.
Suggest me anything I need to do in viewDidLoad
or anywhere else?
Upvotes: 0
Views: 1057
Reputation: 2481
Just declare the array in viewdidload
cartArray = [[NSMutableArray alloc] init];
and remove the array from action event call function.
Upvotes: 0
Reputation: 3408
Because everytime it is initializing your array:
cartArray = [[NSMutableArray alloc] init];
You should not initialize it every time, initialize it once in viewDidLoad
and then add object in button action.
Upvotes: 0
Reputation: 5242
Try this code
- (void)viewDidLoad:(BOOL)animated {
[super viewDidLoad:animated];
cartArray = [[NSMutableArray alloc]init];
}
- (IBAction)clicked:(id)sender {
[cartArray addObject:productName.text];
NSLog(@"Cart Array==%@",cartArray);
}
Upvotes: 1
Reputation: 5092
You are re-creating the cartArray each time the button is pressed, thus overwriting the previous entry. Move the initialisation of the array to viewDidLoad or your init method.
Also productName.text is already a string, there is no need to do the stringWithFormat.
Upvotes: 1