2011-11-28 155 views
0

我真的瘋了這六行代碼。用UITextField瘋狂

注:nomeprezzo 2個文本框

NSString *itemName = (NSString *) [rowVals objectForKey:@"name"]; 
NSString *itemPrice = (NSString *) [rowVals objectForKey:@"price"]; 
nome.text = itemName; 
nome.userInteractionEnabled = YES; 
prezzo.text = itemPrice; 
prezzo.userInteractionEnabled = YES; 

不知道爲什麼,當itemPrice這些標籤的一個複製,該程序在SIGABRT去。 相反,如果我嘗試使用NSLog(@"%@",itemPrice);讀取內容,它會返回確切的值,所以這意味着這是一個有效的NSString

我發現的唯一的解決方案是通過一個NSNumber

NSNumber *itemPrice = (NSNumber *) [rowVals objectForKey:@"price"]; 
prezzo.text = [[NSString alloc] initWithFormat:@"%@", itemPrice]; 

還有另一種方式直接使用NSString

回答

3

@「price」字段中的值可能是NSNumber,而不是NSString。 NSLog方法仍然會提供正確的結果,因爲%@用於任何NSObject子類,而不僅僅是NSString。

+0

權!我沒有檢查。謝謝。 – Oiproks

3

如何:

NSString *itemPrice = [[rowVal objectForKey:@"price"] stringValue]; 
prezzo.text = itemPrice; 
+0

這是另一種解決方案,確實相當不錯。但我正在尋找這個問題。順便謝謝很多。 – Oiproks

0

問題可能是由[rowVals objectForKey:@"price"]返回的對象類型。當你在方法調用之前放置(NSString *)時,你告訴編譯器什麼類型的對象被返回,但實際上並沒有將它轉換成NSString。您在下面使用的行會將NSNumber(或任何其他對象)轉換爲字符串:[[NSString alloc] initWithFormat:@"%@", itemPrice]

0

您可能將NSNumber的對象存儲在NSDictionary而不是NSString中。

可能有兩種方法:一種是將NSNumber轉換爲NSString,另一種方法是將NSNumber轉換爲NSString,同時將其分配給「itemName」。

你可以做轉換爲第二個選項,如:

NSString *itemPrice = [[rowVals objectForKey:@"price"]stringValue]; 
+0

你的解釋是完美的,也是解決方案,但是感謝cpprulez我可以找到解決方案我自己。無論如何,非常感謝這個想法。 – Oiproks