开发者

Port array of strings to array of dictionaries each containing a string

I'm trying to port the strings in an array into an array of dictionaries where each dictionary contains one of the strings and a boolean. Hopefully this makes sense, but I'll try and make a diagram:

At the moment I have:

<array>
-<string1>
-<string2>
...
</array>

But I want:

<array>
-<dictionary1>
--<string1>
--<bool>
-</dictionary1>
-<dictionary2>
--<string2>
--<bool>
-</dictionary2>
...
</array>

I've tried creating a loop to cycle through the array of strings, but it doesn't seem to work.

The ultimate goal is to save this new array of dictionaries to the NSUserDefaults (which I'm also fairly unfamiliar with). This is what I have so far, and any help would be much appreciated!

// Get the current array from the user defaults.
NSArray *tempArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"myArrayKey"];
self.myArray = [tempArray mutableCopy];

// Loop to cycle through the array of strings
for(int i = 0; i < [aList count]; i++)
{
开发者_如何学JAVA    // Boolean to go in the dictionary with the string.
    checked = NO;

    // Create a dictionary, and set it with two objects and two keys. 
   //First object is the string in the array we are cycling through, the second object is the boolean.
    NSDictionary *tempDict = [[NSDictionary alloc] initWithObjectsAndKeys:[aList objectAtIndex:i], @"Title", checked, @"checked", nil];

    // Add this dictionary to the new array of dictionaries.
    [self.myArray addObject:tempDict];

    // This NSLog gives me 0 - but gives me  0 seven times (the number of items in the array I am cycling through) so it is definitely cycling through the array.
    NSLog(@"My Array Count: %i", [myArray count]);

    // Release the tempDict.
    [tempDict release];

}

// Write this new array of dictionaries back to NSUseDefaults.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:myArray forKey:@"myArrayKey"];
[defaults synchronize];


As Daniel pointed out (and I shortly realised through some tests), the fact that the array from NSUserDefaults was nil stopped it from working.


How about inserting a line

[tempDict retain];

next

[self.myArray addObject:tempDict];

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜