0

我正在使用这个方法来初始化一个 nsmutablearray

- (void)getAllContacts
{
Contact *contact = [[Contact alloc] init];
self.allContacts = [[NSMutableArray alloc] init];

int i=0;

for (i=0; i<5; i++) 
{
    contact.nome = [[NSString alloc] initWithFormat:@"Bruno %d", i];    
    [self.allContacts insertObject:contact atIndex:i];
    }
}

很简单!但是之后,我做了一个 for 来打印它的元素,例如:

for (int i=0; i<[self.allContacts count]; i++)
{
    Contact *c = [self.allContacts objectAtIndex:i];
    NSLog(@"i=%d\nNome:%@", i, c.nome);
} 

它会向我显示最后一个元素“Bruno 4”的 5 次。它不是从 0 开始并递增。我应该怎么做才能从0开始?

4

3 回答 3

3

试试这个:

  - (void)getAllContacts
    {
    Contact *contact = nil;
    self.allContacts = [NSMutableArray array];

    int i=0;

    for (i=0; i<5; i++) 
    {
        contact = [Contact new];
        contact.nome = [NSString stringWithFormat:@"Bruno %d", i];    
        [self.allContacts addObject:contact];
        [contact release]
        }
    }

请看一下:内存管理

于 2012-04-17T11:52:30.207 回答
3

因为您在数组中插入了 5 次相同的对象。您需要Contact在每次执行for循环时创建一个新对象。

于 2012-04-17T11:53:01.520 回答
1

您正在做的是实际上在数组中添加了一个 Contact 类的实例 5 次,并且只更改了nome属性。这是执行此操作的正确方法:

- (void)getAllContacts
{
     //alloc init returns a retained object and self.allContacts calls the setter, which    additionally retains it.
    self.allContacts = [[[NSMutableArray alloc] init] autorelease]; 
    int i=0;

    for (i=0; i<5; i++) 
    {
        //Create the Contact object
        Contact *contact = [[Contact alloc] init];
        //Set the nome property
        contact.nome = [NSString stringWithFormat:@"Bruno %d", i];
        //Add the instance to the array
        [self.allContacts addObject:contact];
        //Release the instance because the array retains it and you're not responsible for its memory management anymore.
        [contact release];
    }
}
于 2012-04-17T12:02:32.230 回答