2011-05-09 87 views
0

我正在嘗試在每次迭代中更新循環中的UILabel文本,但它僅顯示最後一個值,是否需要花費時間來完成循環大約是30-50秒。以編程方式更新UILabel

下面是代碼:

for (float i=0; i< [topicNew count]; i++) { 

    NSDictionary *new= [topicNew objectAtIndex:i]; 
    NSString *imageName = [[[NSString alloc] initWithFormat:@"%@.%@.%@.png", appDelegate.subject,topicNamed,[new objectForKey:kWordTitleKey]] autorelease]; 
    NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imageName]; 
    NSData *imageData = [self ParsingImagePath:[new objectForKey:kWordImagePathKey]]; 
    [progressView setProgress:i/[topicNew count]]; 
    [self setProgress:i/[topicNew count]]; 
    [self.lbltest setText:@"Image Downloading..."]; 
    self.lbltest.text =imageName; 
    //NSLog(@"sending %f",i/[topicNew count]); 
    //lblpercent.text = [NSString stringWithFormat:@"%d",i]; 
    [lblpercent setText:[[NSString stringWithFormat:@"%.0f",i/[topicNew count]] stringByAppendingString:@"%"]]; 
    //[self.view addSubview:viewalert]; 
    [self updateLabel:self]; 
    NSLog(@"%@,%d",imageName,i); 
    if(imageData != nil) 
     [imageData writeToFile:imagePath atomically:YES]; 
    else 
     [[NSFileManager defaultManager] removeItemAtPath:imagePath error:NULL]; 

    NSMutableDictionary *newWord = [NSMutableDictionary dictionaryWithObjectsAndKeys:[new objectForKey:kWordTitleKey], kWordTitleKey, [new objectForKey:kWordDefinitionKey], kWordDefinitionKey, imagePath, kWordImagePathKey, appDelegate.subject,kSubjectKey,topicName,kTopicKey,[new objectForKey:kWordMemorizedKey], kWordMemorizedKey, nil]; 
    [newTopic addObject:newWord]; 

} 
+0

回答一個問題是完全不可能的......沒有問題。 – marzapower 2011-05-09 12:32:49

+0

順便說一下,您在哪裏定義了UILabel屬性?您是以編程方式還是通過Interface Builder生成它? – marzapower 2011-05-09 12:33:38

+0

必須在這裏同意marzapower。在我看來,你有兩個問題:你只能得到標籤上的最後一個值,而不是所有的......並且你的循環花費很長時間才能完成。請正確定義您的問題,以便有幫助的人不必提出有關您問題的問題。 – Joetjah 2011-05-09 12:39:02

回答

2

我認爲這個問題是你的線程是由您的環鎖。所以你需要在後臺執行你的方法並使用

[self performSelectorInBackground:@selector(myMethod) withObject:nil]; 

不要忘記把「myMethod」;

-(void)myMethod{ 
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
//I do my label update 
[pool release]; 
} 
+0

謝謝Rohin這對我來說真的很有用。謝謝。 – Arvind 2011-05-09 13:27:53

+0

沒問題,我很高興我幫你! – TheRonin 2011-05-09 13:28:54

0

您現在使用它的方式確實取代了文字。我不知道你想要更新哪個標籤。如果要更新,例如,lbltest有什麼東西被下載的時候,你應該改變self.lbltest.text = imageName;[self.lbltest setText:@"%@ %@", self.lbltest.text, imageName];

這樣一來,你的舊文本不會被你的新的文本替換,但你的新文本被添加到你的舊文本。使用labelName.text = @"Something";將該標籤上的文字更改爲Something

[labelName setText:@"Something"];也是如此。

每當您使用上述兩種方法中的任何一種時,都會將該標籤中的文本替換爲文本「Something」。如果您想爲該標籤添加內容,則必須在舊字符串中包含舊文本。