0

I am pretty new to Objective-C, and trying to create a to-do list app with a table view. I am trying to keep adding strings to my mutable array as the button is pressed. But each time I press the button only the last string gets added to the array.

- (IBAction)notebutton:(UIButton *)sender {

   NSMutableArray *mystr = [[NSMutableArray alloc] init];
   NSString *name = _noteField.text;
   [mystr addObject:name];
   [self.tableView reloadData];
}
4
  • you should create array outside the method and initialize, then add strings to array in method noteButton: Commented Mar 15, 2013 at 0:48
  • Yea that makes sense but where would be a good place to create the array? Commented Mar 15, 2013 at 0:49
  • you can make it in viewDidLoad. just declare it in your .h file and make initilization in viewDidLoad Commented Mar 15, 2013 at 0:53
  • it is explained in answer below very well Commented Mar 15, 2013 at 0:53

2 Answers 2

5

Do not declare the NSMutableArray each time. Declare it only once.

Make NSMutableArray *mystr; as a property and allocate it in viewDidLoad() once.

in .h or .m file

@property(nonatomic,strong) NSMutableArray *mystr;

viewDidLoad()

self.mystr = [[NSMutableArray alloc] init];

- (IBAction)notebutton:(UIButton *)sender {

   NSString *name = _noteField.text;
   [self.mystr addObject:name];
   [self.tableView reloadData];
}
Sign up to request clarification or add additional context in comments.

1 Comment

then I get this error "Initializer element is not a compile-time constant"
0

You Are creating mutable array on method. so each time its Allocating and making new array.

Just allocate the nsmutable array in viewdidload/viewdidappear and add object in your method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.