Question

I have an array that loads information from a plist like so:

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

Here is how the plist looks like:

<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>

I have also created a for-loop that creates a UIButton for every string there is in the plist, how do I check in the loop if the index contain a 'data' key? I would like to check if the index has data so I can set an image to the button.

Was it helpful?

Solution

Something like this should work:

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 ...

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top