简体   繁体   中英

Can't add objects to a NSMutableArray

So I have the following code:

NSMutableArray *array
array=[[NSMutableArray alloc] init];
[array addObject: object1];
[array addObject: object2];
NSLog(@"%@",array);

When I use the app in my iPod connected to my Mac, NSLog writes just null, I don't get object1 object2. What am I doing wrong?

PS: array is a property in .h @property (nonatomic, retain) NSMutableArray *array;

应该是:

array=[[NSMutableArray alloc] init];

Your [[NSMutableArray array] init] should be [[NSMutableArray alloc] init] . That would work but its not a proper way to initialize objects. You didn't post what your array is, i assume you declared it wrong. It should be a pointer to a NSMutableArray object. Here is a working code:

NSMutableArray *array=[[NSMutableArray alloc] init];
[array addObject: @"a"];
[array addObject: @"b"];
NSLog(@"%@",array);

You are not initializing your array at all, that's why it doesn't return anything.

array=[[NSMutableArray alloc] init];
[array addObject: object1];
[array addObject: object2];
NSLog(@" Array is:%@",array);

Remember to release it afterwards(unless you are using ARC)

You could try doing it in one line.

 NSMutableArray *array = [[NSMutableArray alloc] arrayWithObjects:@"a", @"b", nil];
 NSLog(@"%@",array);

You declared array as a property. Its corresponding iVar gets initialized to nil. So in your init method you have to initialize it:

Assuming you used

@synthesize array;

In your init method

if (self) {
//other init stuff
array = [[NSMutableArray array] retain];
}

Then when adding stuff

[self.array addObject: object];

Also note that he objects you put in there have to be properly initialized and r not nil. So try to log this too

NSLog("the object %@ was put in array. Array contains: %@",object, self.array);

And in dealloc, release your array!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM