Read Array from plist

Discussion in 'iOS Development' started by wyndwarrior, Jun 17, 2010.

  1. wyndwarrior

    wyndwarrior Active Member

    Joined:
    Jun 8, 2009
    Messages:
    1,433
    Likes Received:
    1
    Device:
    3G iPod touch
    So, I have a plist that looks something like this:
    Code:
    <key>list</key>
    <array>
    <string>1</string>
    <string>2</string>
    <string>3</string>
    <string>4</string>
    </array>
    Now how would I be able to read it, format it into an NSArray and then display it through something like a UITableView?
  2. NolesFans

    NolesFans New Member

    Joined:
    Sep 23, 2008
    Messages:
    404
    Likes Received:
    0
    Device:
    iPod touch
    if you read the docs for NSArray, you can see about arrayWithContentsOfFile or initWithContentsOfFile.
  3. gojohnnyboi

    gojohnnyboi Well-Known Member

    Joined:
    Jan 25, 2008
    Messages:
    3,339
    Likes Received:
    55
    What you have is a regular dictionary, and an array for the key "list". Read in the file as an NSDictionary, then instantiate an NSArray by calling objectForKey:
  4. wyndwarrior

    wyndwarrior Active Member

    Joined:
    Jun 8, 2009
    Messages:
    1,433
    Likes Received:
    1
    Device:
    3G iPod touch
    Thanks,

    Is it also possible to have the array by itself without a key?
  5. SkylarEC

    SkylarEC Super Moderator Emeritus Staff Member

    Joined:
    Sep 19, 2007
    Messages:
    6,642
    Likes Received:
    129
    Yes. And it is preferable to creating a dictionary with a key for every entry in the array. In your plist, it will look like
    HTML:
    <array>
                    <integer>0</integer>
                    <integer>0</integer>
                    <integer>0</integer>
            </array>
    
    The sample shows contains only integers. What <type> of storage is used is chosen appropriately by the frameworks when you create the array.

    You'd put an array into a plist the same way you'd put any other NSObject into a plist.
  6. lauNchD

    lauNchD Well-Known Member

    Joined:
    Jan 27, 2008
    Messages:
    1,844
    Likes Received:
    261
    Device:
    iPhone 5 (Black)
    I think what you mean is making the entire plist file an array, like this:
    HTML:
    <!-- fancy doctype plist header here -->
    
    <array> <!-- instead of dict -->
            <string>blah</string>
            <integer>2</integer>
    </array>
    
    <!-- fancy footer here -->
    Then just use what NolesFans pointed out.

    (BTW: In the Property List Editor, if you use it, you can simply change the root object's type.)

Share This Page