简体   繁体   English

比较Objective-C中的2个对象

[英]Compare 2 Objects in Objective-C

In my application, I want to compare 2 core data instances of the entity "Workout". 在我的应用程序中,我想比较实体“ Workout”的2个核心数据实例。 I want to check if the 2 objects have identical attribute values for all of their attributes. 我想检查2个对象的所有属性是否具有相同的属性值。 Essentially if the two objects are the same minus the relationship, whosWorkout. 本质上,如果两个对象相同,则减去关系,即whosWorkout。 Is there any way to do this without manually checking every single attribute? 没有手动检查每个属性的方法,有没有办法做到这一点? I know I could do: 我知道我可以做:

if(object1.intAttr == object2.intAttr){
    NSLog(@"This attribute is the same");
}
else{
    return;
}

repeat with different attributes...

Is there any core data method to make this a bit less tedious? 是否有任何核心数据方法可以使此操作变得更简单?

First I would create an isEqual method in the Workout subclass like this... 首先,我将像这样在Workout子类中创建isEqual方法。

-(BOOL)isEqualToWorkout:(Workout*)otherWorkout
{
    return [self.attribute1 isEqual:otherWorkout.attribute1]
        && [self.attribute2 isEqual:otherWorkout.attribute2]
        && [self.attribute3 isEqual:otherWorkout.attribute3]
        && [self.attribute4 isEqual:otherWorkout.attribute4]
        ...;
}

Then whenever you want to compare to Workout objects just use... 然后,每当您想与“ Workout对象进行比较时,只需使用...

BOOL equal = [workout1 isEqualToWorkout:workout2];

You can iterate through the attributes by name. 您可以按名称遍历属性。

for (NSString *attribute in object.entity.attributesByName) {
    if ([[object  valueForKey:attribute] intValue] != 
        [[object2 valueForKey:attribute] intValue]) {
       return NO;
    }
}
return YES;

This assumes all integer attributes. 这假定所有整数属性。 You could do a switch statement to check for the class with the class method and deal with different data types as well. 您可以执行switch语句以使用class方法检查该类,并处理不同的数据类型。

If you need to compare whether one object represents a greater or lesser value than another object, you can't use the standard C comparison operators > and <. 如果需要比较一个对象代表的值大于还是小于另一个对象,则不能使用标准的C比较运算符>和<。 Instead, the basic Foundation types, like NSNumber, NSString and NSDate, provide a compare: method: 相反,基本的Foundation类型(例如NSNumber,NSString和NSDate)提供了compare:方法:

if ([someDate compare:anotherDate] == NSOrderedAscending) {

    // someDate is earlier than anotherDate

}

I ended up doing the following: 我最终做了以下工作:

-(BOOL)areEqual:(Workout *)firstWorkout secondWorkout:(Workout *)secondWorkout{
    NSArray *allAttributeKeys = [[[firstWorkout entity] attributesByName] allKeys];

    if([[firstWorkout entity] isEqual:[secondWorkout entity]]
       && [[firstWorkout committedValuesForKeys:allAttributeKeys] isEqual:[secondWorkout committedValuesForKeys:allAttributeKeys]]) {
        return YES;
    }
    else{
        return NO;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM