0

我想比较两个数组的等效对象,一个是我的类中的属性,另一个是我的测试方法中的属性。

我无法直接比较,因为对象将被单独分配,因此具有不同的内存位置。

为了解决这个问题,我在我的对象上实现了描述,以在字符串中列出它的属性:(vel 是一个 CGPoint)

- (NSString *)description {
return [NSString stringWithFormat:@"vel:%.5f%.5f",vel.x,vel.y];
}

我测试:

NSLog(@"moveArray description: %@",[moveArray description]);
NSLog(@"currentMoves description: %@", [p.currentMoves description]);

[[theValue([moveArray description]) should] equal:theValue([p.currentMoves description])];

我的 NSLog 的产量:

Project[13083:207] moveArray description: (
"vel:0.38723-0.92198"
)

Project[13083:207] currentMoves description: (
"vel:0.38723-0.92198"
)

但是我的测试失败了:

/ProjectPath/ObjectTest.m:37: error: -[ObjectTest example] : 'Object should pass test' [FAILED], expected subject to equal <9086b104>, got <7099e004>

theValue 用字节和 Objective-C 类型初始化 KWValue,并用

- (id)initWithBytes:(const void *)bytes objCType:(const char *)anObjCType {
if ((self = [super init])) {
    objCType = anObjCType;
    value = [[NSValue alloc] initWithBytes:bytes objCType:anObjCType];
}

return self;
}

我如何比较这两个数组具有等效值的对象?

4

2 回答 2

3

您的测试失败,因为您正在比较指针地址,而不是值。

您可以遍历一个数组并将每个对象与第二个数组中等效定位的对象进行比较。确保您的比较针对您要比较的值类型正确完成。如果每个元素都有不同的类型,那么它会变得更棘手。

// in some class
- (BOOL)compareVelocitiesInArray:(NSArray *)array1 withArray:(NSArray *)array2
{
    BOOL result = YES;

    for (uint i = 0; i < [array1 count]; i++) {
        CustomObject *testObj1 = [array1 objectAtIndex:i]
        CustomObject *testObj2 = [array2 objectAtIndex:i]

        // perform your test here ...
        if ([testObj1 velocityAsFloat] != [testObj2 velocityAsFloat]) {
            result = NO;
        }
    }

    return result;
}

// in another class
NSArray *myArray = [NSArray arrayWithObjects:obj1, obj2, nil];
NSArray *myOtherArray = [NSArray arrayWithObjects:obj3, obj4, nil];
BOOL result;

result = [self compareVelocitiesInArray:myArray withArray:myOtherArray];
NSLog(@"Do the arrays pass my test? %@", result ? @"YES" : @"NO");
于 2011-10-05T23:19:33.850 回答
0

用 Kiwi 比较两个数组的内容相同的另一种可能性:

[[theValue(array1.count == array2.count) should] beTrue];
[[array1 should] containObjectsInArray:array2];
[[array2 should] containObjectsInArray:array1];

比较计数可确保数组之一不包含多次对象,因此确保它们真的相等。

于 2015-01-27T09:54:31.107 回答