views:

523

answers:

1

I need to build an NSString that resembles the following:

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

Where:

  • each line (e.g. Telephone) is included or excluded based on the value of a UISwitch
  • the key part of the string (i.e. the part to the left of the ':') is localized
  • the value part is from a UITextField.

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:

  • is this a decent approach (i'm an objective-c noob)?
  • i realize that my array is autoreleased, but still i'm concerned about memory usage. should i release the auto-release pool? seems a bit dangerous.
  • i'm hoping to make the code a bit more dynamic. my initial thought is to create an array of outlet variables, then use the UISwitch's tag to store the key that drives the localization. thoughts?

Thanks for your time,

Craig Buchanan

A: 

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.

Dustin Voss
I'm assuming that the local, autorelease variables are automatically assigned to a locally-created autorelease pool, correct? Do you find yourself using this frequently?If I understand your last suggestion, I would have an instance-level NSIndexSet variable that would altered on the IBAction method that is assigned to the UISwitches? That variable would be used in a for loop by the method that creates the dynamic string to drive the localization process. True?Thanks.
Craig
The answer is "yes" to everything you said, except that I don't use local autorelease pools frequently, since I usually use the alloc/init pattern in tight loops.
Dustin Voss