How to get a specific object from data structure based on Index

57 views Asked by At

I am creating a custom UIPageViewController which uses a custom setup. The data structure that I have is parsed into the following format:

{
    "1.0" =     (
                {
            detail = "Detail 0";
            icon = "Pull to Refresh";
            title = "Item 0";
        },
                {
            detail = "More easily refresh a subscription or playlist.";
            icon = "Pull to Refresh";
            title = "Pull to Refresh";
        }
    );
    "1.1" =     (
                {
            detail = "Create custom stations of your favorite podcasts.";
            icon = Stations;
            title = "Custom Stations";
}

When each sub content view controller is created for the Page View I have the index, in the above case it would be 0,1,2. But in 'real life' it could be 0-10 for example.

How do I get the relevant sub dictionary reference from the index?

As an example, if the index was 1, I would want to get the NSDictionary:

{
            detail = "More easily refresh a subscription or playlist.";
            icon = "Pull to Refresh";
            title = "Pull to Refresh";
}

The part I am unsure about is that within the overall NSDictionary of data I have sub NSArray's with different counts of objects.

1

There are 1 answers

0
TylerP On BEST ANSWER

Get the keys of the dictionary:

NSArray *keys = yourMainDictionary.allKeys;

Sort this array by treating the keys as version numbers, since that's what they appear to be (based on your data structure format):

NSArray *sortedKeys = [keys sortedArrayUsingComparator:^(NSString *key1, NSString *key2) {
    return [key1 compare:key2 options:NSNumericSearch];
}];

Iterate over these keys and add each array's sub-dictionaries to a mutable array:

NSMutableArray *allDictionaries = [NSMutableArray array];
for (NSString *key in sortedKeys) {
    NSArray *subDictionaries = yourMainDictionary[key];
    [allDictionaries addObjectsFromArray:subDictionaries];
}

You now have an array of all the sub dictionaries called allDictionaries. So, if you have an index, you just access it like any other array, for example:

NSDictionary *dictionaryWithIndex1 = allDictionaries[1];

... should give you:

{
    detail = "More easily refresh a subscription or playlist.";
    icon = "Pull to Refresh";
    title = "Pull to Refresh";
}