cocoa question

Hi all,
Newbie here. I was working on a challenge from Aaron’s book:
Challenge: Make a Data Source
Make a to-do list application. The user will type tasks into the text field. When the user clicks the Add button, you will add the string to a mutable array, and the new task will appear at the end of the list.

While I was trying to solve it on my own, I did this:

I used to see in the console that ‘string’ was added to toDoList array but I could not get the ‘string’ to appear
in the TableView.

However, I later saw that I should have done:

This one change alone was required to get the application working the way I wanted it to.

Can someone explain me the importance of using init method to initialize the array toDoList instead of my earlier method?

Hi,

as far as I can see, you want to use NSMutableArray toDoList as a variable in your class which is accessible from every method. Therefore you must declare toDoList as an instance variable.

The .h file should include

[code]@interface MyClass : NSObject {
NSMutableArray *toDoList;
}

@end[/code]
and in the .m file the instance variable is initialized in the init method (as you described).
In a Memory Management environment you must also add a release message in the dealloc method.

- (void)dealloc { [toDoList release]; [super dealloc]; }
In your self-made method you’re going to initialize a new array every time the method will be called.
This is certainly not intended. In the repeat loop the class of the index variable must be NSString, because you add a string to the Array

- (IBAction) createNewItem: (id) sender { NSString *string = [textField1 stringValue]; NSLog(@"%@", string); [toDoList addObject: string]; for (NSString *aItem in toDoList) { NSLog(@"%@", aItem); } }

Thanks.
I am presently not interested in Memory Management since I am using Leopard and I can use garbage collector.

Yes, that’s improper. Actually, I had trouble understanding why the string (even if just one) contained in the array was not getting displayed in the TableView. Now, I have figured out that it was because I had earlier omitted to use [tv1 reloadData];

Thanks, I missed that.