Search code examples
iosgenstrings

iOS - genStrings -s not able to use replacement function


iOS has a genStrings function to help localize calls from NSLocalizedString (and related functions) to a output file of key value pairs for translation.

take a look at my .h file :

   #import <UIKit/UIKit.h>

@interface ViewController : UIViewController

-(NSString*)CustomLocalizedString :(NSString*) key defaultString:(NSString*)comment;

@end

here CustomLocalizedString will be my replacement function instead of NSLocalizedString.

Lets see the .m implementation file:

    #import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self CustomLocalizedString:@"my key" defaultString:@"my default"];
}



-(NSString*)CustomLocalizedString:(NSString *)key defaultString:(NSString *)comment{

    NSString*  mystring= NSLocalizedString(key ,comment);

    return mystring;
}
@end

When i go to the command line to run genStrings and tell it to use my custom function:

genstrings -o . -s CustomLocalizedString ViewController.m

but the results are odd:

  Bad entry in file ViewController.m (line = 19): Argument is not a literal string.
    Bad entry in file ViewController.m (line = 24): Argument is not a literal string.
    Bad entry in file ViewController.m (line = 26): Argument is not a literal string.

If we examine the output file called Localizable.strings it looks like this:

 ?%%

Solution

  • I found the issue. It seems the custom function must follow the exact same method signature as the NSLocalizedString function. I was using

    [self CustomLocalizedString:@"my key" defaultString:@"my default"];
    

    i changed it to

    CustomLocalizedString(@"my key",@"my default");
    

    and this resolved the issue. You might have to name the function just as i did as well prefixing the LocalizedString portion but double check if im write on that part.