NSMutablearray从最后一个元素而不是第一个元素开始打印

时间:2012-04-17 11:50:33

标签: ios arrays for-loop nsmutablearray objective-c-blocks

我正在使用此方法初始化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 (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开始?

3 个答案:

答案 0 :(得分: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]
        }
    }

请看一下:Memoy Management

答案 1 :(得分:3)

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

答案 2 :(得分: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];
    }
}