My goal is to add a string to array, and I do that in a method which I call.
In this method, I get a null value in the array, and don't know why. I have this at the start of my class:
NSMutableArray *listOfEvents;
and a method which I call on each event:
-(void)EventList
{
[listOfEvents addObject:@"ran"];
NSLog(@"%@", listOfEvents);
}
I get (null)
in the log.
If I put the array definition NSMutableArray *listOfEvents;
in the function body, I get the string value @"ran"
, each time, so the array always has only one value, instead of having many strings named @"ran"
.
What's wrong with this? It seems that I can't understand something about arrays, even though I have read the documents a number of times.
I'm assuming you haven't initialized
listOfEvents
.Make sure you do
listOfEvents = [[NSMutableArray alloc] init];
in your class'sinit
method. Also make sure you release it in your class'sdealloc
method.Apparently you're not initializing your array.
If that's your problem, I suggest reading the docs again. And not the NSMutableArray docs. Go back to The Objective-C Programming Language and others.
You need to
alloc
theNSMutableArray
. Try doing this first -NSMutableArray *listOfEvents = [[NSMutableArray alloc] init];
After this you could do what you what you planned...
If you're getting
nil
in your log message, you need to make sure listOfEvents is non-nil before adding your object. IE:In Objective-C, messages with
void
return types sent tonil
go to absolutely-silent nowhere-land.Also, for the sake of balance, be sure you have a
[listOfEvents release]
call in yourdealloc
implementation.