【问题标题】:R.array.string equivalent in iOSiOS 中的 R.array.string 等效项
【发布时间】:2013-12-16 21:37:43
【问题描述】:

我正在开发一个 iOS 应用程序,以前只在 android 中开发。在 android 中,可以将字符串和字符串数组存储在资源文件中,然后再引用它们。这使得实际代码看起来更整洁。有没有办法在 iOS 中做到这一点?

【问题讨论】:

    标签: android ios objective-c arrays string


    【解决方案1】:

    您可以将数据存储在 plist 中,然后将其反序列化为字典(或者甚至只是一个数组,如果您不需要灵活的话)。有关文档,请参阅NSPropertyListSerializationhttps://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSPropertyListSerialization_Class/Reference/Reference.html#//apple_ref/occ/clm/NSPropertyListSerialization/propertyListWithData:options:format:error 上的类文档:

    例如,如果您有以下名为 my_resources.plist 的 plist 文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>MyStringArray</key>
        <array>
            <string>String One</string>
            <string>String Two</string>
        </array>
    </dict>
    </plist>
    

    您可以加载它(假设它在捆绑包中):

    NSError* error = nil;
    NSURL* resourceFile = [[NSBundle mainBundle] URLForResource:@"my_resources" withExtension:@"plist"];
    NSData* resourceData = [NSData dataWithContentsOfURL:resourceFile options:0 error:&error];
    if (resourceData) {
      NSDictionary* resources = [NSPropertyListSerialization propertyListWithData:resourceData options:0 format:NULL error:&error];
      if (resources) {
        NSArray* myArray = resources[@"MyStringArray"];
        NSString* stringOne = myArray[0]; // returns "String One"
        NSString* stringTwo = myArray[1]; // returns "String Two"
        // do something with the resources
      } else {
        NSLog(@"Error: Could not read plist data from %@: %@", resourceFile, error);
      }
    } else {
      NSLog(@"Error: Could not read file data at %@: %@", resourceFile, error);
    }
    

    【讨论】:

    • 不同语言的同一个数组呢?
    【解决方案2】:

    首先:在 *.plist 文件部分添加以下字符串

    <plist version="1.0">
    <dict>
        <key>MyStringArray</key>
        <array>
            <string>String One</string>
            <string>String Two</string>
        </array>
    </dict>
    </plist>
    

    第二:在你的源代码下面添加,

    SWIFT 4

    let myStringArray = Bundle.main.infoDictionary!["MyStringArray"] as! NSArray
    for string in myStringArray {
        print(string)
    }
    

    【讨论】:

    • 虽然这可能回答了这个问题,但它看起来并不是一个完整的答案。 MyStringArray 在哪里定义?属性文件?该文件中的内容是什么样的?
    • 我已经更新了我的答案,谢谢。 @ChristopherSchneider
    【解决方案3】:

    检查NSLocalizedString

    可用于本地化的键/值字符串

    【讨论】:

    • 链接丢失
    猜你喜欢
    • 1970-01-01
    • 2012-08-03
    • 2011-10-29
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 2014-06-19
    • 1970-01-01
    相关资源
    最近更新 更多