xcode

2011-06-14 25 views
0

如何調用xcode中的新函數,並且我正在執行此代碼來填充具有註釋標題的表視圖,但函數被多次調用並且表格單元格中填充了所有重複的值,如何所謂在Xcode的功能,如何從停止此功能獲取調用不止一次xcode

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{  
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) 
    { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
    } 
    NSLog(@"this is a test text   "); 
    NSMutableArray *annotations = [[NSMutableArray alloc] init]; 
    int i=0; 
    if(indexPath.section == 0) 
    { 
     for(iCodeBlogAnnotation *annotation in [map annotations]) 
     { 
      i++; 
      NSLog(@"this is the no %d",i); 
      [annotations addObject:annotation]; 
     } 

     cell.textLabel.text = [[annotations objectAtIndex:indexPath.row] title]; 
    } 

    return cell; 
} 

任何幫助深表感謝, 感謝您的幫助提前

+0

Xcode不調用函數。 – BoltClock 2011-06-14 16:34:04

+0

你能幫我嗎我怎麼才能找出爲什麼for循環運行不止一次,謝謝 – jarus 2011-06-14 16:36:57

+0

每次調用方法都會運行'for'循環,每當UITableView需要一個單元時,循環就會發生。 – Anomie 2011-06-14 16:40:15

回答

2

你不能真正控制當它被調用時。每次你的tableview想要顯示一個新的單元格時都會調用它。您可以使用indexPath來確定放入該單元格的內容。它至少在屏幕上每個單元格調用一次(有時如果表格上下滾動,則更多)。

你不需要每次這個函數被調用時創建的臨時數組,只需使用[map annotations]直接:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    // There will be one row per annotation 
    return [[map annotations] count] 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{  
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) 
    { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
    } 

    // Put the text from this annotation into this cell 
    cell.textLabel.text = [[[map annotations] objectAtIndex:indexPath.row] title]; 

    return cell; 
} 

我希望我理解你的問題。如果沒有,請在下面的評論中告訴我!

+0

謝謝你的幫助我新來xcode,我來自PHP的背景,所以如果你有任何教程鏈接,可以幫助我過渡到xcode我真的很感激它 – jarus 2011-06-14 16:46:19

+0

我剛剛通過試驗和錯誤,並提出問題使用stackoverflow!)我沒有遵循任何特定的教程。 – deanWombourne 2011-06-14 17:11:47

1

它不是一個函數,它是一個方法。

當表視圖繪製單元格時,它由表視圖調用。它將在每個單元格中調用一次,有時每個單元格會調用一次以上,具體取決於用戶正在做什麼。

您不會將數據推入表視圖,它會要求您輸入單元格內容。

問:「我怎麼能阻止這個函數被多次調用?」表明你不理解表格視圖(如果你來自UI編程的「推送」模型,這很令人困惑)。從TableView programming guide開始。

0

只要UITableView沒有特定索引路徑的UITableViewCell並且需要一個,就會調用該函數。請注意,由於用戶滾動(爲了節省內存,可能會重新使用或釋放​​屏幕外的單元格)或調用reloadData及相關函數或insertRowsAtIndexPaths:withRowAnimation:及相關函數,可能會多次調用索引路徑。你不能(並且真的不想)阻止它被多次調用。

也就是說,假設[map annotations]返回某種排序的集合,每次都以相同的方式排序,您的代碼應該做你想做的事情(即使效率非常低)。有關該問題的更多細節將會有所幫助。