Search code examples
iosiphonelocalizable.strings

Read values from localized file iOS


I have created a localized string file which contains Error message in Key/Value Pair. What I just want to read values on key basis just like Plist.

Here is content of my Localized file

"SERVICE_ERROR" = "Some error occurred while processing your request, Please try later";

And this is how I am saving this string in user preferences

[ErrorManager setLastErrorInPreferences:NSLocalizedString(@"SERVICE_ERROR", nil)];

Here is setLastErrorInPreferences method

+ (void)setLastErrorInPreferences:(id)errorString {
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSDate *now = [NSDate date];
    NSString *errorStringWithTime = [NSString stringWithFormat:@"On %@:\n%@", now, errorString];
    [prefs setObject:errorStringWithTime forKey:KlastError];
}  

But its not working. Its just saving the key as it is. Its not reflecting the value of this key in user preferences.Kindly let me know what I am missing.


Solution

  • I am assuming you have a Localizable.strings file. No other name will work.
    Change the content of your localizable file from

    "SERVICE_ERROR" = "Some error occurred while processing your request, Please try later";
    

    to

    SERVICE_ERROR = "Some error occurred while processing your request, Please try later";
    

    (Remove "" from your key SERVICE_ERROR and keep a semi-colon at the end ;)

    Also show what your setLastErrorInPreferences is doing?

    Usage

    NSString* error = NSLocalizedString(@"SERVICE_ERROR", nil);   
    NSLog(@"%@",error);
    

    It worked fine.

    My File

    enter image description here

    EDIT

    Fetching the errorValue. Make some method in your ErrorManager class and fetch it from there as kLastError won't be available in your Controller class.

    NSString* yourError = [[NSUserDefaults standardUserDefaults] stringForKey:KlastError];