为 UITextField 疯狂
这六行代码让我简直要疯了。
注意:nome
和 prezzo
是 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
吗?
I'm literally going crazy whit these six rows of code.
NB: nome
and prezzo
are 2 textFields
NSString *itemName = (NSString *) [rowVals objectForKey:@"name"];
NSString *itemPrice = (NSString *) [rowVals objectForKey:@"price"];
nome.text = itemName;
nome.userInteractionEnabled = YES;
prezzo.text = itemPrice;
prezzo.userInteractionEnabled = YES;
Don't know why when itemPrice
is copied in one of those label, the program go in SIGABRT.
Instead if I try to read the content with an NSLog(@"%@",itemPrice);
it return the exact value, so it means that is a valid NSString
.
The only solution I found is passing through a NSNumber
:
NSNumber *itemPrice = (NSNumber *) [rowVals objectForKey:@"price"];
prezzo.text = [[NSString alloc] initWithFormat:@"%@", itemPrice];
There is another way to use directly the NSString
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
@"price" 字段中的值可能是 NSNumber,而不是 NSString。 NSLog 方法仍然会提供正确的结果,因为 %@ 用于任何 NSObject 子类,而不仅仅是 NSString。
Probably the value in the @"price" field is NSNumber, and not an NSString. The NSLog method will still provide a correct result, since %@ is used for any NSObject subclass, not just NSString.
这个怎么样:
How about this:
问题可能是
[rowVals objectForKey:@"price"]
返回的对象类型。当您将(NSString *)
转换放在方法调用之前时,您是在告诉编译器返回什么类型的对象,但实际上并没有将其转换为 NSString。下面使用的行确实从 NSNumber (或任何其他对象)转换为字符串:[[NSString alloc] initWithFormat:@"%@", itemPrice]
The problem might be the object type returned by
[rowVals objectForKey:@"price"]
. When you place the(NSString *)
cast before the method call, you're telling the compiler what type of object is returned, but not actually converting it into an NSString. The line you use below does convert from NSNumber (or whatever other object) to a string:[[NSString alloc] initWithFormat:@"%@", itemPrice]
您可能将 NSNumber 的对象存储在 NSDictionary 而不是 NSString 中。
可能有两种方法:一种是将 NSNumber 转换为 NSString,同时将其添加到字典中,另一种方法是将 NSNumber 转换为 NSString,同时将其分配给“itemName”。
您可以对第二个选项进行转换,例如:
You might be storing NSNumber's object in NSDictionary instead of NSString.
There could be 2 ways: one would be to convert NSNumber to NSString while adding it to dictionary or the other way would be to convert NSNumber to NSString while assigning it to "itemName".
you may do the conversion for second option like: