0

所以我有以下代码:

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

当我在连接到 Mac 的 iPod 中使用该应用程序时,NSLog 只写入 null,我没有得到 object1 object2。我究竟做错了什么?

PS:数组是.h中的一个属性@property (nonatomic, retain) NSMutableArray *array;

4

5 回答 5

2

应该是:

array=[[NSMutableArray alloc] init];
于 2012-06-02T10:39:32.067 回答
0

您可以尝试在一行中完成。

 NSMutableArray *array = [[NSMutableArray alloc] arrayWithObjects:@"a", @"b", nil];
 NSLog(@"%@",array);
于 2012-06-02T10:54:23.840 回答
0

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!

于 2012-06-02T11:30:54.290 回答
0

[[NSMutableArray array] init]应该是[[NSMutableArray alloc] init]。这会起作用,但它不是初始化对象的正确方法。您没有发布您array的内容,我假设您声明它是错误的。它应该是一个指向NSMutableArray对象的指针。这是一个工作代码:

NSMutableArray *array=[[NSMutableArray alloc] init];
[array addObject: @"a"];
[array addObject: @"b"];
NSLog(@"%@",array);
于 2012-06-02T10:40:18.383 回答
0

你根本没有初始化你的数组,这就是它不返回任何东西的原因。

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

记得之后释放它(除非你使用 ARC)

于 2012-06-02T10:46:33.577 回答