ios - convert NSArray to NSDictionary

安稳与你 提交于 2019-12-13 04:19:21

问题


i want to convert an nsarray to nsdictionary i'm using to

- (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array
{
    id objectInstance;
    NSUInteger indexKey = 0;

    NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
    for (objectInstance in array)
        [mutableDictionary setObject:objectInstance forKey:[NSNumber numberWithUnsignedInt:indexKey++]];

    return (NSDictionary *)[mutableDictionary autorelease];
}

output result is:

{
    0 =     {
        Event = "";
        ID = 1;    };
    3 =     {
        Event = "";
        ID = 77;    };
    2 =     {
        Event = "";
        ID = 23;    };
    1 =     {
        Event = "";
        ID = 45;    };
    7 =     {
        Event = "";
        ID = 10;    };
    5 =     {
        Event = "";
        ID = 26;    };
    6 =     {
Event = "";
        ID = 27;
    };
    8 =     {
Event = "";
        ID = 28;
    };
}

After convert to nsdictionary, the order of nsdictionary isn't true to the original order, i want to display the same order in nsarray, i don't know how? can you help me?


回答1:


NSDictionary does not have an order. Sort the keys and use them to access the entries.




回答2:


If I understand correctly from your responses to @ACB and @Zaph in the comments, you want to do the following:

Maintain a collection mapping integer keys to object values which is ordered by the keys.

If I'm understanding correctly, an array won't be good enough for your purposes because the integer keys in an array allow for no "holes". You, however, need to allow for holes: in the output in your question, the key-value pair for 4 is missing. For this reason, a dictionary is appealing to you.

Unfortunately, a dictionary will not allow you to maintain an ordering on the key-value pairs it contains, as @Zaph points out. You say, however, you just want to display the values in the dictionary ordered by the keys in a UITableView. Presumably, it is unimportant the order in which the dictionary is serialized to disk (using writeToFile:atomically:) so long as the contents of the dictionary are displayed in the correct order in the table view.

A dictionary can be used for this purpose as follows. First, we'll need a class PFXKeyValuePair;

@interface PFXKeyValuePair : NSObject
@property (nonatomic) id<NSCopying> key;
@property (nonatomic) id value;
+ (PFXKeyValuePair *)pairWithValue:(id)value forKey:(id<NSCopying>)key;
+ (NSArray *)pairsWithValues:(NSArray *)values forKeys:(NSArray *)keys;
@end

@implementation PFXKeyValuePair
+ (PFXKeyValuePair *)pairWithValue:(id)value forKey:(id<NSCopying>)key
{
    PFXKeyValuePair *pair = [[PFXKeyValuePair alloc] init];
    pair.value = value;
    pair.key = key;
    return pair;
}
+ (NSArray *)pairsWithValues:(NSArray *)values forKeys:(NSArray *)keys
{
    NSAssert(values.count == keys.count, @"The array of values must be the same size as the array of keys.");
    NSUInteger count = values.count;
    NSMutableArray *mutableRes = [NSMutableArray array];
    for (NSUInteger index = 0; index < count; index++) {
        PFXKeyValuePair *pair = [PFXKeyValuePair pairWithValue:values[index] forKey:keys[index]];
        [mutableRes addObject:pair];
    }
    return [mutableRes copy];
}
@end

Second, we'll need a category method on NSDictionary:

@interface NSDictionary (PFXAdditions)
- (NSArray *)pfx_keyValuePairsSortedByKeyUsingComparator:(NSComparator)comparator;
@end

@implementation NSDictionary (PFXAdditions)
- (NSArray *)pfx_keyValuePairsSortedByKeyUsingComparator:(NSComparator)comparator
{
    NSArray *sortedKeys = [self.allKeys sortedArrayUsingComparator:comparator];
    NSArray *sortedValues = [self objectsForKeys:sortedKeys notFoundMarker:[NSNull null]];
    return [PFXKeyValuePair pairsWithValues:sortedValues forKeys:sortedKeys];
}
@end

Note: In the above, PFX and pfx are placeholders. You ought to replace them with prefixes appropriate to your project.

We can then use this category method when to populate our UITableView. Let's say we have a property

@property (nonatomic) NSDictionary *events;

And let's assume that the table view has only one section in which these events will be shown.

Then we can implement –tableView:numberOfRowsInSection: in our UITableViewController subclass as follows:

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.events.count;
}

And within our implementation of –tableView:numberOfRowsInSection: we can determine the appropriate entry in the dictionary to use as follows:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //...
    NSArray *pairs = [self.events pfx_keyValuePairsSortedByKeyUsingComparator:^(id obj1, id obj2) {
        NSNumber *key1 = (NSNumber *)obj1;
        NSNumber *key2 = (NSNumber *)obj2;
        return [key1 compare:key2];
    }];

    NSUInteger index = [indexPath indexAtPosition:1];
    PFXKeyValuePair *pair = pairs[index];
    /*
    At this point, pair.value will be a dictionary as in your output above 
    holding a value for the key @"Event" and a value for the key @"ID".
    */
    //...
}

This could be made faster by making pairs a property and only computing it when necessary (for example, by only computing pairs just prior to reloading the table's data).

Note: Using this approach, the dictionary will still not be serialized to disk (when calling -writeToDisk:atomically:) "in order" and your output will still look the same as in your question. However, this does not matter: when the data is displayed to the user in the table view, the data will be ordered as you're hoping.




回答3:


This is example one of the exmple get the emplyee list NSMutableArray and create NSMutableDictionary.......

NSMutableArray *emloyees = [[NSMutableArray alloc]initWithObjects:@"saman",@"Ruchira",@"Rukshan",@"ishan",@"Harsha",@"Ghihan",@"Lakmali",@"Dasuni", nil];

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *word in emloyees) {

NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
letterList  = [dict objectForKey:firstLetter];

if (!letterList) {
    letterList = [NSMutableArray array];
    [dict setObject:letterList forKey:firstLetter];
}

[letterList addObject:word];}NSLog(@"dic %@",dict);


来源:https://stackoverflow.com/questions/14179354/ios-convert-nsarray-to-nsdictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!