Plist 没有用于代码的单独“格式”(这个问题按原样不太有意义)。您要么想要 1. 生成使用这些值初始化字典的 Objective-C 代码,要么 2. 使用文件初始化字典,您可以为此编写
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"UIPhoneFormats.plist"];
编辑:所以你想生成Objective-C代码,反过来会重现相同的字典。为此,您需要以格式化的方式重新打印字典的内容。你可以编写这样的程序:
#import <stdio.h>
#import <Foundation/Foundation.h>
NSString *recursiveDump(id object)
{
if ([object isKindOfClass:[NSString class]]) {
return [NSString stringWithFormat:@"@\"%@\"", object];
} else if ([object isKindOfClass:[NSNumber class]]) {
return [NSString stringWithFormat:@"@%@", object];
} else if ([object isKindOfClass:[NSArray class]]) {
NSMutableString *str = [NSMutableString stringWithString:@"@["];
NSInteger size = [object count];
NSInteger i;
for (i = 0; i < size; i++) {
if (i > 0) [str appendString:@", "];
[str appendString:recursiveDump([object objectAtIndex:i])];
}
[str appendString:@"]"];
return str;
} else if ([object isKindOfClass:[NSDictionary class]]) {
NSMutableString *str = [NSMutableString stringWithString:@"@{"];
NSString *key;
NSInteger size = [object count];
NSArray *keys = [object allKeys];
NSInteger i;
for (i = 0; i < size; i++) {
if (i > 0) [str appendString:@", "];
key = [keys objectAtIndex:i];
[str appendFormat:@"%@: %@", recursiveDump(key), recursiveDump([object objectForKey:key])];
}
[str appendString:@"}"];
return str;
} else {
// feel free to implement handling NSData and NSDate here,
// it's not that straighforward as it is for basic data types.
}
}
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"UIPhoneFormats.plist"];
NSMutableString *code = [NSMutableString stringWithString:@"NSDictionary *dict = "];
[code appendString:recursiveDump(dict)];
[code appendString:@";"];
printf("%s\n", [code UTF8String]);
[pool release];
return 0;
}
该程序将从提供的属性列表中生成(希望没有语法错误)Objective-C 初始化代码,可以将其复制粘贴到项目中并使用。
编辑:我只是在 OP 提供的 plist 文件的剥离版本上运行程序(原始文件太大,所以我把它剪掉了一点),它生成了以下代码:
NSDictionary *dict = @{@"at": @[@"+43 1 ########", @"+43 ############", @"01 ########", @"00 $"], @"ar": @[@"+54## #### ####", @"## #### ####", @"00 $", @"18 ### $ "]};
为了验证它是否真的有效,我将它粘贴int main()
到一个名为“test.m”的文件的中间,所以我得到了这个程序:
#import <Foundation/Foundation.h>
int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDictionary *dict = @{@"at": @[@"+43 1 ########", @"+43 ############", @"0$
NSLog(@"%@", dict);
[pool release];
return 0;
}
为了验证,我运行clang -o test test.m -lobjc -framework Foundation
并惊讶,惊讶:
有效。
编辑2:我把它做成了一个命令行实用程序,只是为了方便进一步的工作——谁知道呢,这将来可能有用。Plist2ObjC
希望这可以帮助。