After checking a number of topics, I still can't figure something out : what is the (best?) way to use static NSLocalizedString, i.e. to statically allocate a NSLocalizedString and access it easily.

Ideally, I would want to do something like that (which won't compile, with an Initializer element is not a compile-time constant error):

 //Somewhere in my header
 static NSString* mystring = NSLocalizedString(@"min", nil); //Error : "Initializer element is not a compile-time constant"

 @implementation myClass
 (NSString*)aMethod
{
    return myString;
}
@end

I know NSLocalizedString is a macro defined by
#define NSLocalizedString(key, comment) \ [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil],
but that is not helping much :S.

Why ?

Long story short, to prevent the multiple definition of the same string in multiple parts of a document (which would prevent a one-stroke edit in my whole app).

Consider the example, where the redundancy of the definition is quiet explicit :

//MyDelegate.h
@property IBoutlet NSTextField* myTextField;

//MyDelegate.m
@implementation MyDelegate.m
@synthetize myTextField;
-(void)setTextFieldToDefaultValue
{
    [myTextField setStringValue:NSLocalizedString(@"Name",@"This field is used to write one's name");
}
-(BOOL)isTextFieldStringDefault:(NSString*)myString
{
    return [[myTextField stringValue] isEqual:NSLocalizedString(@"Name",@"This field is used to write one's name")];
}
@end

Of course, it makes more sense in a project which is quiet dense and big, where the string would be used in difference methods, and in a context where you have use of a lot of similar localized strings.

有帮助吗?

解决方案

Generally this should all be in your implementation file:

static NSString* myString = nil;

@implementation myClass

+ (void)initialize
{
    myString = NSLocalizedString(@"min", nil);
}

- (NSString *)aMethod
{
    return myString;
}

@end

其他提示

Well one more way you can write the same without using initialize method above:-

static NSString* mystring=nil;
-(NSString*)aMethod
{
    mystring = NSLocalizedString(@"min", nil);
    return mystring;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top