本文介绍了ios - 将 NSArray 转换为 NSDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个 nsarray 转换为我正在使用的 nsdictionary

- (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array{id 对象实例;NSUInteger indexKey = 0;NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];for(数组中的对象实例)[mutableDictionary setObject:objectInstance forKey:[NSNumber numberWithUnsignedInt:indexKey++]];返回(NSDictionary *)[mutableDictionary autorelease];}

输出结果为:

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

转换成nsdictionary后,nsdictionary的顺序和原来的顺序不一样,我想在nsarray中显示同样的顺序,不知道怎么做?你能帮我吗?

解决方案

如果我从您在评论中对@ACB 和@Zaph 的回复中理解正确,您希望执行以下操作:

维护一个将整数键映射到按键排序的对象值的集合.

如果我理解正确,数组将不足以满足您的目的,因为数组中的整数键不允许空洞".但是,您需要考虑漏洞:在您问题的输出中,缺少 4 的键值对.出于这个原因,一本字典对你很有吸引力.

不幸的是,正如@Zaph 指出的那样,字典不允许您维护它包含的键值对的排序.但是,您说,您只想显示按 UITableView 中的键排序的字典中的值.据推测,字典序列化到磁盘的顺序(使用 writeToFile:atomically:)并不重要,只要字典的内容在表视图中以正确的顺序显示即可.>

字典可用于此目的,如下所示.首先,我们需要一个 PFXKeyValuePair 类;

@interface PFXKeyValuePair : NSObject@property (nonatomic) id<NSCopying>钥匙;@property (nonatomic) id 值;+ (PFXKeyValuePair *)pairWithValue:(id)value forKey:(id)key;+ (NSArray *)pairsWithValues:(NSArray *)values forKeys:(NSArray *)keys;@结尾@implementation PFXKeyValuePair+ (PFXKeyValuePair *)pairWithValue:(id)value forKey:(id)key{PFXKeyValuePair *pair = [[PFXKeyValuePair alloc] init];pair.value = 值;pair.key = 密钥;返回对;}+ (NSArray *)pairsWithValues:(NSArray *)values forKeys:(NSArray *)keys{NSAssert(values.count == keys.count, @"值的数组必须和键的数组大小相同.");NSUInteger count = values.count;NSMutableArray *mutableRes = [NSMutableArray 数组];for (NSUInteger index = 0; index 

其次,我们需要一个 NSDictionary 的分类方法:

@interface NSDictionary (PFXAdditions)- (NSArray *)pfx_keyValuePairsSortedByKeyUsingComparator:(NSComparator)comarator;@结尾@implementation NSDictionary (PFXAdditions)- (NSArray *)pfx_keyValuePairsSortedByKeyUsingComparator:(NSComparator)comarator{NSArray *sortedKeys = [self.allKeys sortedArrayUsingComparator:comarator];NSArray *sortedValues = [self objectsForKeys:sortedKeys notFoundMarker:[NSNull null]];返回 [PFXKeyValuePair pairWithValues:sortedValues forKeys:sortedKeys];}@结尾

注意:上面的PFXpfx是占位符.您应该用适合您项目的前缀替换它们.

然后我们可以在填充我们的 UITableView 时使用这个类别方法.假设我们有一个属性

@property (nonatomic) NSDictionary *events;

我们假设表格视图只有一个部分将显示这些事件.

然后我们可以在我们的 UITableViewController 子类中实现 –tableView:numberOfRowsInSection: 如下:

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

在我们的 –tableView:numberOfRowsInSection: 实现中,我们可以确定字典中要使用的适当条目,如下所示:

- (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;返回 [key1 比较:key2];}];NSUInteger index = [indexPath indexAtPosition:1];PFXKeyValuePair *pair =pairs[index];/*此时,pair.value 将是一个字典,如上面的输出保存键@"Event" 的值和键@"ID" 的值.*///...}

通过将 pairs 设为属性并仅在必要时计算它(例如,仅在重新加载表的数据之前计算 pairs),可以加快速度.

注意:使用这种方法,字典仍然不会被序列化到磁盘(当调用 -writeToDisk:atomically: 时)按顺序",你的输出仍然会看起来和你的问题一样.但是,这并不重要:当数据在表格视图中显示给用户时,数据将按照您希望的顺序进行排序.

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?

解决方案

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

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.

这篇关于ios - 将 NSArray 转换为 NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:46