转换任何数据类型的NSString

问题描述:

cell.textField.text = [contact valueForKey:formCell.variableName]; 

的valueForKey我得到的是未知类型的,也可以是的NSNumber,整数,浮点,NSString的..转换任何数据类型的NSString

我想价值的NSString转换。使用的NSString stringWithFormat

,应指定格式说明,对象的类型是在运行时已知

+1

contact是NSdictionary .. ?? – userar 2012-01-11 09:13:27

  1. valueForKey:的价值永远不会返回intfloat。相反,它会将它们包装成NSNumber s。详细信息here

  2. 因此,您可以使用"%@"代表他们stringWithFormat:

  3. 您还可以使用description方法NSObject这样的:[[contact valueForKey:formCell.variableName] description]

+0

有趣的是NSNumber。最后的代码在我的情况'[NSString stringWithFormat:@“%@”,[dict valueForKey:@“key”]]' – 2016-08-29 08:16:21

cell.textField.text = [NSString stringWithFormat:@"%@",[contact valueForKey:formCell.variableName]]; 
+0

你也可以像这样使用NSObject的描述方法:[[contact valueForKey:formCell.variableName] description]。 – Hanuman 2012-01-11 11:08:29

有一个-description消息,任何对象的作品从NSObject下降:

cell.textField.text = [[contact valueForKey:…] description]; 

使用%@格式说明符在后台调用-description,因此两者大部分是等效的,只有直接调用-description更短,可能更有效。

,你可以尝试使用的描述方法:

cell.textField.text = [[contact valueForKey:formCell.variableName] description]; 

通常情况下,它的实现为字符串,表示对象

description:是一种方法,你可以调用任何NSObject,它应该返回一个NSString *描述文本。

http://developer.apple.com/library/mac/ipad/#documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html

有些情况下,它会甚至可以自动地叫你的。