2016年12月1日 星期四

讓NSLocalizedString自動讀Base.lproj

#ifndef L
#define L(key) [NSBundle.mainBundle localizedStringForKey:(key)]
#endif
@interface NSBundle (NSLocalizedString_Base)
- (NSString *)localizedStringForKey:(NSString *)key;
@end
@implementation NSBundle (NSLocalizedString_Base)
- (NSString *)localizedStringForKey:(NSString *)key {
NSString * s = [self localizedStringForKey:key value:@"" table:nil];
if ([s isEqualToString:key]) {
NSString * path = [[NSBundle mainBundle] pathForResource:@"Base" ofType:@"lproj"];
NSBundle * languageBundle = [NSBundle bundleWithPath:path];
s = [languageBundle localizedStringForKey:key value:@"" table:nil];
}
if (s == nil) {
s = key;
}
return s;
}
@end

讓obj-c也可以跟swift一樣,enum支援字串

#define LIST_OF_ServerAPI \
/*會員*/ \
api(登入, member/login) \
api(FB登入, member/fbLogin)
typedef NS_ENUM(NSInteger, ServerAPI) {
#define api(key, name) key,
LIST_OF_ServerAPI
#undef api
};
- (void)call {
NSString *apiKey;
NSString *apiName;
switch (api) {
#define api(key, name) \
case key: \
apiKey = @#key; \
apiName = @#name; \
break;
LIST_OF_ServerAPI
#undef api
default:
NSAssert1(false, @"%@:ServerAPI未實作", NSStringFromSelector(_cmd));
return;
}
}