ios - 从数组索引 obj c 加载某些信息

标签 ios objective-c arrays plist

我有一个数组,可以像这样从 plist 加载信息:

NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:@"items.plist"];

这是 plist 的样子:

<array>
<dict>
    <key>string</key>
    <string>STR</string>
    <key>id</key>
    <string>0</string>
</dict>
<dict>
    <key>string</key>
    <string>STR2</string>
    <key>id</key>
    <string>1</string>
</dict>
<dict>
    <key>string</key>
    <string>STR3</string>
    <key>id</key>
    <string>2</string>
</dict>
<dict>
    <key>string</key>
    <string>STR4</string>
    <key>id</key>
    <string>35</string>
    <key>data</key>
    <string>5</string>
</dict>
</array>

我还创建了一个 for 循环,它为 plist 中的每个字符串创建一个 UIButton,如果索引包含“数据”键,我该如何检查循环? 我想检查索引是否有数据,以便我可以为按钮设置图像。

最佳答案

像这样的东西应该可以工作:

NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:@"items.plist"];
for (NSDictionary * dict in array) {
    UIButton * newBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [newBtn setTitle:dict[@"id"] forState:UIControlStateNormal];

    // -- Update for comment -- //
    // See if data exists
    if (dict[@"data"]) {
        // if data's value is an image ...
        [newBtn setImage:dict[@"data"] forState:UIControlStateNormal];

        // In your question the values for @"data" are integers, so make sure you don't try to add that as an image.

    }

    // do other stuff with button ...

}

关于ios - 从数组索引 obj c 加载某些信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22546950/

相关文章:

ios - 当用户快速点击一个单元格时触发一个 Action

ios - 如何从我的数组中删除 "..."?

ios - 在一个标签字符串中显示两种不同类型的变量

iphone - 将 iPad 2 中的相机锁定为横向模式

objective-c - 为 OSX 10.6 编译时找不到 NSExpression

python - 在 numpy 数组中查找子数组的索引

php - 将字符串分解为二维数组

ios - Swift-在标签栏 Controller 中自定义多个导航栏

ios - 围绕居中的 UIView 约束多个 UIView

ios - SiriKit 错误 : Donating intent is not supported by this application