2011-11-28 158 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