NSDictionary:比较NSDictionaries

时间:2013-10-13 22:50:03

标签: objective-c data-structures nsmutablearray

有两个文件。让我们称他们为fileOnefileTwo

每个都有几个名称相同的NSMutableDictionary属性。列举几个:

@property (retain, nonatomic) NSMutableDictionary * lunchStartTimeObject;
@property (retain, nonatomic) NSMutableDictionary * lunchLocationNameObject;
@property (retain, nonatomic) NSMutableDictionary * lunchLocationAddressObject;
@property (retain, nonatomic) NSMutableDictionary * activity1NameObject;
@property (retain, nonatomic) NSMutableDictionary * activity1StartTimeObject;
@property (retain, nonatomic) NSMutableDictionary * activity1LocationNameObject;
@property (retain, nonatomic) NSMutableDictionary * activity1CommentsFieldObject;
@property (retain, nonatomic) NSMutableDictionary * activity1LocationAddressObject;
@property (retain, nonatomic) NSMutableDictionary * activity2NameObject;
@property (retain, nonatomic) NSMutableDictionary * activity2StartTimeObject;
@property (retain, nonatomic) NSMutableDictionary * activity2LocationNameObject;
@property (retain, nonatomic) NSMutableDictionary * activity2CommentsFieldObject;
@property (retain, nonatomic) NSMutableDictionary * activity2LocationAddressObject;

我想通过调用下面的方法(或类似的东西)来比较两个文件中具有相同名称的词典:

-(NSMutableDictionary *)cellColorForChanges:(NSMutableDictionary *)newdictionary :(NSMutableDictionary *)oldDictionary;
{
    if(![newdictionary isEqualToDictionary:oldDictionary])
    {
        [newdictionary  setValue:@"UIColor yellowColor" forKey:@"cellColor"];
    }
    return newdictionary;
}

我正在尝试避免手动为每个NSMutableDictionary编写代码。有没有办法避免以下情况:

if(![fileOne.lunchStartTimeObject isEqualToDictionary:fileTwo.lunchStartTimeObject])
{  
    fileOne.lunchStartTimeObject setValue:@"UIColor yellowColor" forKey:@"cellColor"]; 
}

我无法找到实现上述目标的最有效方法。是否有可能将每个字典发送到一个方法并返回字典(用另一个键更新,如果它不相等)?或者我想避免的是不可避免的?

1 个答案:

答案 0 :(得分:0)

您遇到了这个问题,因为您没有充分抽象对象。在我看来,上面的财产清单是多余的。即使您提供的简单代码也难以读取。

尝试以更概念的方式思考您的问题。尝试考虑可以封装您正在寻找的功能的对象。

查看您的属性,您可能需要这样的类

@interface Activity : NSObject

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSDate *startTime;
@property (nonatomic, strong) Location *location;

-(BOOL)isEqualToActivity:(Activity*)activity;

@end

也许您需要一个位置类来存储有关位置的更多信息;也许你可以使用更多的字段,如firstName,lastName;也许你需要一个type(枚举或字符串)属性来告诉它是什么样的活动,等等 - 你明白了。

如上所示,您可以编写自己的比较方法,您可以调整以允许更多或更少的严格资本或小写字母,数字格式等。