Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic, localized NSString

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

like image 387
craig Avatar asked Jul 04 '26 07:07

craig


1 Answers

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.

like image 183
Donovan Voss Avatar answered Jul 07 '26 06:07

Donovan Voss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!