Cannot add items to an NSMutableArray ivar

2018-12-31 17:15发布

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.

4条回答
浪荡孟婆
2楼-- · 2018-12-31 17:19

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.

查看更多
荒废的爱情
3楼-- · 2018-12-31 17:23

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楼-- · 2018-12-31 17:24

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...

查看更多
裙下三千臣
5楼-- · 2018-12-31 17:26

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.

查看更多
登录 后发表回答