craig
craig

Reputation: 26262

Dynamic, localized NSString

I need to build an NSString that resembles the following:

Name: Craig Buchanan
Telephone: 800-555-1212
Email: [email protected]

Where:

My approach:

NSMutableArray *values = [[NSMutableArray alloc] initWithCapacity:3];

if (self.nameSwitch.isOn) 
    [values addObject:[NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"Name", @"Name label"), textFieldName.text]];
if (self.telephoneSwitch.isOn)
    [values addObject:[NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"Telephone", @"Telephone number label"), textFieldTelephone.text]];
if (self.emailSwitch.isOn)
    [values addObject:[NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"Email", @"Email address label"), textFieldEmail.text]];

return [values componentsJoinedByString:@"\r"];

I have a few questions:

Thanks for your time,

Craig Buchanan

Upvotes: 3

Views: 2307

Answers (1)

Donovan Voss
Donovan Voss

Reputation: 1460

Your target language might not use colons, so just make calls like this to add the localized lines:

[values addObject:[NSString stringWithFormat:NSLocalizedString(@"Name: %@", @"Name line"), name];

As for the autorelease question, you can make a local autorelease pool:

NSAutoreleasePool *myPool = [[NSAutoreleasePool alloc] init];
// Do stuff.
[myPool release];

Finally, you can use the switch's tag to indicate an array index. If you do that, you won't even need an IBOutlet variable for the switch; you can just use -viewForTag: or the argument to the action method. You can use NSIndexSet to store the switch state if you like. But if you want to be dynamic, you should probably use a table to hold the switches. If you do that, you can use the table row number instead of a tag.

Upvotes: 1

Related Questions