【问题标题】:Unable to populate array using plist无法使用 plist 填充数组
【发布时间】:2013-07-30 10:19:47
【问题描述】:

我正在尝试使用 Plist 填充我的数组。这是我的 plist 文件,Menu.plist。

-第0项,类型:字典,值(1项)-标题,字符串,联系人

-第1项,类型:字典,值(1项)-标题,字符串,编辑

  - (void)viewDidLoad
    {
        [super viewDidLoad];
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Menu" ofType:@"plist"];
        self.menuArray = [NSMutableArray arrayWithContentsOfFile:plistPath];


    }

我正在尝试使用单元格联系人和编辑填充我的表格视图,但我的 menuArray 没有被加载,我检查了 NSLog 并且 *plist 正在获取路径,但在 self.menuArray 它仍然显示 0 个对象,而它应该是 2。我以前做过这个,它工作得很好我不知道今天出了什么问题。有什么建议吗???

【问题讨论】:

  • 如果你查看你的 plist 文件,它应该是 NSDictionary 而不是 NSArray
  • 显示实际的 plist 文本并检查它是否已添加到目标中(因此复制到应用程序中)。
  • 可以把内容粘贴到plist吗?
  • @Gamerlegend 您可以在文本编辑器中打开 plist 并粘贴其内容吗?

标签: ios objective-c plist nsbundle


【解决方案1】:

根据您的问题,plist 内容如下

XML 格式

<?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">
<array>
    <dict>
        <key>Title</key>
        <string>Contact</string>
    </dict>
    <dict>
        <key>Title</key>
        <string>Edit</string>
    </dict>
</array>
</plist>

如果是这种情况,请尝试以下操作

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Menu" ofType:@"plist"];
NSArray *menuDataArray = [NSMutableArray arrayWithContentsOfFile:plistPath];

NSLog(@"Plist Content Array = %@", menuDataArray);

输出

Plist Content Array = (
        {
        Title = Contact;
    },
        {
        Title = Edit;
    }
)

注意:

  • 请检查您的 Plist 结构。
  • 数组分配初始化。

【讨论】:

    【解决方案2】:

    试试这个

    - (void)viewDidLoad
        {
            [super viewDidLoad];
            self.menuArray=[[NSMutableArray alloc]init];
            NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Menu" ofType:@"plist"];
            self.menuArray = [NSMutableArray arrayWithContentsOfFile:plistPath];
    
    
        }
    

    你必须分配 NSMutableArray。

    【讨论】:

    • 尝试分配 alloc NSMutableArray,但没有奏效,menuArray.count 仍然返回 0 个对象。我检查了我的一个旧程序,并且相同的代码在那里运行良好,这是在不使用 ARC 的情况下完成的,这个项目使用 ARC,它会有什么不同,如果是这样,我应该做些什么改变?
    【解决方案3】:

    你能粘贴你的 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">
    <array>
        <string>Brand A</string>
        <string>Brand B</string>
        <string>Brand C</string>
        <string>Brand D</string>
    </array>
    </plist>
    

    在您的情况下,您可能尝试从基于字典的 plist 创建 NSArray。你应该使用:

    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    

    如果该字典的某些对象是数组,您可以通过以下方式获取它:

    NSArray *array = [dict objectForKey:@"KeyForSomeArray"];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多