Two Face
Two Face

Reputation: 87

Neater way to write all these parameters

I have a bunch of saved nsuserdefault parameters that need to be written (20 cars to be exact). I am wondering what will be the neatest way to write this. I number it in order because I believe the for loop will be appropriate(not too sure). The code below represents a snippet of what I am trying to do.

         NSString *emailBody=[NSString                            
         stringWithFormat:@"%@, %@, %@",[[NSUserDefaults        
         standardUserDefaults]stringForKey:@"Car1"],[[NSUserDefaults 
         standardUserDefaults]stringForKey:@"Car2"],[[NSUserDefaults 
         standardUserDefaults]stringForKey:@"Car3"]];

Upvotes: 0

Views: 71

Answers (3)

Rob Napier
Rob Napier

Reputation: 299275

There's no reason to save 20 separate items. Just put them in an array and store the array with setObject:forKey:. You can then fetch them all back as an array using stringArrayForKey: (or arrayForKey: or even just objectForKey:).

Once you have an array, creating a comma-separated list is very easy:

NSString *emailBody = [array componentsJoinedByString:@", "];

If you must store them as 20 items for compatibility, I would still pull them out of NSUserDefaults and put them in an array before actually using them.

Upvotes: 2

trojanfoe
trojanfoe

Reputation: 122381

Slightly neater:

NSMutableString *emailBody = [[NSMutableString alloc] init];
for (unsigned i = 1; i <= 20; i++) {
    if (i > 1)
        [emailBody appendString:@", "];
    [emailBody appendString:[[NSUserDefaults standardUserDefaults]
        stringForKey:[StringWithFormat:@"Car%d", i]]];
}

Upvotes: 0

TheAmateurProgrammer
TheAmateurProgrammer

Reputation: 9392

Just use a for loop, something like this.

NSMutableArray *a = [NSMutableArray array];
for (int i=1;i<21;i++)
{
    [a addObject:[NSString stringWithFormat:@"Car%d", i]];
}

Then just put the array into a string.

Upvotes: 0

Related Questions