0

Basically I have two sections in my app one call cars and the other call trucks each with 3 buttons. When one button is click it saves the truck or car details in nsuserdefault. Bascially I want to print it out in an email showing the cars and truck the user clicked on and show it in a specific format for example "Car:Car1,Car 2, Car 3 Truck: Truck1, Truck2 Truck 3".However, if the user clicked on 2 car buttons and one Truck button it looks like this "Car:Car1,Car2,Truck1" Any tips on how to get around this will be appreciated.

              NSString *emailBody=[NSString                            
             stringWithFormat:@"Car:%@,%@,%@,Truck:%@,%@,%@",[[NSUserDefaults        
             standardUserDefaults]stringForKey:@"Car1"],[[NSUserDefaults 
             standardUserDefaults]stringForKey:@"Car2"],[[NSUserDefaults 
             standardUserDefaults]stringForKey:@"Car3"],[[NSUserDefaults 
             standardUserDefaults]stringForKey:@"Truck1"],[[NSUserDefaults 
             standardUserDefaults]stringForKey:@"Truck2"],
             [[NSUserDefaults standardUserDefaults]stringForKey:@"Truck3"]];
4

2 回答 2

0

好吧,我个人认为您不应该为此使用 NSUserDefaults 。您应该考虑创建一个自定义数据结构来容纳所有信息,然后将其存储到文档目录中的 plist 中。

通过这种方式,您可以创建一个字典数组,其中每个字典包含汽车/卡车的名称、一个用于判断对象是汽车还是卡车的键,以及一个用于确定汽车/卡车是当前选择。这样,当需要格式化电子邮件时,您只需定义一个简单的循环来计数并列出汽车和卡车。

于 2013-08-20T02:02:19.053 回答
0

尝试这样的事情:

NSString *emailBody=[NSString stringWithFormat:@"Car:%@,%@,%@,Truck:%@,%@,%@",
[[NSUserDefaults standardUserDefaults]stringForKey:@"Car1"] ?: @"",
[[NSUserDefaults standardUserDefaults]stringForKey:@"Car2"] ?: @"",
[[NSUserDefaults standardUserDefaults]stringForKey:@"Car3"] ?: @"",
[[NSUserDefaults standardUserDefaults]stringForKey:@"Truck1"] ?: @"",
[[NSUserDefaults standardUserDefaults]stringForKey:@"Truck2"] ?: @"",
[[NSUserDefaults standardUserDefaults]stringForKey:@"Truck3"] ?: @""];

这样,如果您以前从未设置过其中一个键,它将被一个空字符串替换。

不过,我同意0x7fffffff我宁愿为该功能使用一系列字典。当您需要持久化数据时,必须使用用户默认值,我不确定是否是您的情况。

于 2013-08-20T02:06:02.113 回答