1

我有一个包含字典的数组。

将新项目添加到数组时,我想将它们添加到顶部或更新字典,具体取决于我添加的键是否存在。如果该键不存在字典,我想将其添加到顶部。否则我想用那个键更新字典。

我们如何在 Objective-C 中做到最好?

NSMutableArray * mediaData = [[NSMutableArray alloc] init];
for (int k=0; k<mediaData.count; k++)
{
    NSDictionary   *dict = [NSDictionary dictionaryWithObject: @"String1" forKey: @"Test"];
    [mediaData add:dict];
}

如果它与上述键存在(例如“String1”),我们如何更新字典值,如果不存在,如果列表中不存在具有键的字典,我们将如何附加到数组的顶部。

如果代码中存在语法错误,请致歉。这只是为了让您了解问题所在。

4

1 回答 1

2

好的,这是未经测试的,有点笨拙,但我认为它符合您的要求:

我的列表.h:

#import <Cocoa/Cocoa.h>

@interface MyList : NSObject {
    NSMutableArray *_array;
}

- (void)addOrUpdateObject:(NSObject *)value
                   forKey:(NSString *)key;

@end

然后实现将类似于:

我的列表.m:

#import "MyList.h"

@implementation MyList

- (id)init {
    self = [super init];
    if (self != nil) {
        _array = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)addOrUpdateObject:(NSObject *)value
                   forKey:(NSString *)key {

    for (NSUInteger i = 0; i < _array.count; i++) {
        NSMutableDictionary *dict = [_array objectAtIndex:i];
        NSArray *allKeys = [dict allKeys];
        for (NSUInteger j = 0; j < allKeys.count; j++) {
            NSString *existingKey = [allKeys objectAtIndex:j];
            if ([existingKey isEqualToString:key]) {
                [dict setObject:value forKey:key];
                return;    // Updated
            }
        }
    }

    // Key not found; create a new dictionary
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setObject:value forKey:key];
    [_array insertObject:dict atIndex:0];
}

@end
于 2013-07-08T11:09:57.690 回答