问题
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.
回答1:
I'm assuming you haven't initialized listOfEvents
.
Make sure you do listOfEvents = [[NSMutableArray alloc] init];
in your class's init
method. Also make sure you release it in your class's dealloc
method.
回答2:
If you're getting nil
in your log message, you need to make sure listOfEvents is non-nil before adding your object. IE:
-(void)EventList
{
if (listOfEvents == nil) {
listOfEvents = [[NSMutableArray alloc] init];
}
[listOfEvents addObject:@"ran"];
NSLog(@"%@",listOfEvents);
}
In Objective-C, messages with void
return types sent to nil
go to absolutely-silent nowhere-land.
Also, for the sake of balance, be sure you have a [listOfEvents release]
call in your dealloc
implementation.
回答3:
Apparently you're not initializing your array.
NSMutableArray *listOfEvents = [[NSMutableArray alloc] init];
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.
回答4:
You need to alloc
the NSMutableArray
. Try doing this first -
NSMutableArray *listOfEvents = [[NSMutableArray alloc] init];
After this you could do what you what you planned...
来源:https://stackoverflow.com/questions/7125326/cannot-add-items-to-an-nsmutablearray-ivar