我通过做一种连接而遇到麻烦;
我收到4个不同的数据,我用“[dico objectForKey:@”alertSerie“]”(例如)。 必须使用在屏幕上引入数据的String显示数据。 我必须将这些数据放在一个UITextField中。
示例:
[dico objectForKey:@"alertfriend"] = Beth
[dico objectForKey:@"alertmom"] = Lise
[dico objectForKey:@"alertgirlf"] = Angela
text for Beth will be "This is my friend :"
text for Lise will be "This is my mom :"
text for Angela will be "This is my girlfriend :"
在UITextField中,我想显示:
This is my friend :Beth
This is my mom : Lise
This is my girlfriend : Angela
直到现在没关系,代码如下:
field.text = [NSString stringWithFormat:@"NThis is my friend : %@\nTHis is my mom : %@\nThis is my girlfriend : %@\n",[dico objectForKey:@"alertfriend"], [dico objectForKey:@"alertmom"], [dico objectForKey:@"alertgfriend"] ];
现在,有可能一个人没有朋友,没有妈妈或没有女朋友......
我该怎么办?
我尝试了很多可能性但是我们不能连接对象这一事实对我来说并不常见,而且在这种情况下它会引起我的问题......
非常感谢您的关注!!!
编辑:
我试过那段代码但是有错误; ]或其他什么......
if ([dico objectForKey:@"alertSerie"]) {
NSString *serie = [NSString stringWithFormat:@"Numéro de série : %@\n", [dico objectForKey:@"alertSerie"] ];}
else {
NSString *serie = [NSString stringWithFormat:@" "] ];}
if ([dico objectForKey:@"alertDate"]) {
NSString *date = [NSString stringWithFormat:@"Date de mise en service : %@\n", [dico objectForKey:@"alertDate"] ];}
else {
NSString *date = [[NSString stringWithFormat:@" "] ];}
if ([dico objectForKey:@"alertCli"]) {
NSString *cli = [NSString stringWithFormat:@"Nom du client associé : %@\n", [dico objectForKey:@"alertCli"] ];}
else {
NSString *cli = [NSString stringWithFormat:@" "] ];}
答案 0 :(得分:1)
您需要检查此人是否有朋友,女朋友和妈妈。这意味着您必须使用条件。这可以通过使用一些简单的if语句来完成。
NSMutableString *text = [[NSString alloc] init];
if([dico objectForKey:@"alertmom"] != nil)
{
[text appendFormat:@"This is my Mom: %@ \n", [dico objectForKey:@"alertmom"]];
}
if([dico objectForKey:@"alertfriend"]!= nil)
{
[text appendFormat:@"This is my friend: %@ \n", [dico objectForKey:@"alertfriend"]];
}
if([dico objectForKey:@"alertgirlf"] != nil)
{
[text appendFormat:@"This is my girlfriend: %@ \n", [dico objectForKey:@"alertgirlf"]];
}
field.text = text;
答案 1 :(得分:1)
您可以简单检查密钥是否存在,否则使用空字符串:
NSString *mom = [dico objectForKey:@"alertmom"];
if (mom == nil)
mom = @"";
您还可以进一步创建一个简单的功能:
-(NSString *) getValueFromKey:(NSString* )theKey inDictionary:(id)theDic {
if([theDic objectForKey:theKey] == nil)
return @"";
else
return [theDic objectForKey:theKey];
}
答案 2 :(得分:1)
NSMutableString *string = [[NSMutableString alloc] init];
if([dico objectForKey:@"alertfriend"] != nil)
{
[string appendString:[NSString stringwithformat:@"This is my friend: %@ \n",[dico objectForKey:@"alertfriend"]];
}
如果字典的返回值不等于nil,则以类似的方式追加其他字符串。