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クラスの1つのインスタンスを配列に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 に答える