将新对象添加到NSMutableArray

问题描述:

我有一个名为Profile的自定义类和一个NSMutableArray,我添加了配置文件对象,以防我需要在迭代中来回切换。将新对象添加到NSMutableArray

的代码是这样的:

@try { 
    currentProfile = (Profile *) [cache objectAtIndex:(int)currentPosition-1]; 
} 
@catch (NSException * e) { 
    Profile *cached = [[Profile alloc] init]; 
    [cached loadProfile:currentPosition orUsingUsername:nil appSource:source]; 
    cached.position = NULL; 
    [cache addObject:cached]; 
    currentProfile = cached; 
    [cached release]; 
} 

//And the "log" i use to show the error 
Profile *temp; 
for (int i=0; i<[cache count]; i++) { 

    temp = (Profile *) [cache objectAtIndex:(int)currentPosition-1]; 
    NSLog(@"%@ - %d e %d", temp.name, temp.position, temp.realId); 
} 
[temp release]; 

的是NSLog的返回我的缓存时间lenght与同一个对象。 I.E.
为LEN = 1: 第一 - 1个E 1

为LEN = 2:
第二 - 2 e 2的
第二 - 2 e 2的

为LEN = 3:
第三 - 3 E 3
第三 - 3 E 3
第三 - 3 E 3

等等...
而我需要的是:
为LEN = 3:
第一 - 1个E 1
第二 - 2 e 2的
第三 - 3 E 3

你可能想使用可变i在循环内,代替currentPosition

for (int i=0; i<[cache count]; i++) { 
    temp = (Profile *) [cache objectAtIndex:i]; 
    NSLog(@"%@ - %d e %d", temp.name, temp.position, temp.realId); 
} 

否则,您总是检索相同的对象。

您可能还想考虑'for each'循环,而不是简单的'for'。只是为了简单起见。

for (Profile *temp in cache) { 
    NSLog(@"%@ - %d e %d", temp.name, temp.position, temp.realId); 
} 
+1

^^你回答快,不需要在同一职位的2倍,从而删除矿 – 2011-02-23 00:38:53

+0

@Jason查看[stackapps(http://stackapps.com/),他们有一些有用的通知公用事业:) – 2011-02-23 00:42:13

+0

上帝,谢谢!这很快,非常有用。我觉得很愚蠢=( – 2011-02-23 01:00:54