2011-02-23 115 views
2

我有一個名爲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

回答

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

相關問題