【问题标题】:Subtract values in Array2 from Array1 while keeping remaining duplicates从 Array1 中减去 Array2 中的值,同时保留剩余的重复项
【发布时间】:2012-03-03 23:12:59
【问题描述】:

是否可以从另一个 NSMutableArray 中的值中减去一个 NSMutableArray 中的值,同时保留任何剩余的类似值(保留重复副本)?我不想删除值的每个实例,只是 1 减 1。

我正在使用 CGPoints。

数组1 CCP(1,1) CCP(1,1) CCP(1,2) ccp(1,3)

数组2 ccp(1,1)

所需输出:Array3 CCP(1,1) CCP(1,2) ccp(1,3)

【问题讨论】:

    标签: objective-c arrays


    【解决方案1】:

    抱歉,我之前没有正确理解您的问题。也许您可以尝试以下方法:

    NSMutableArray *points1 = [NSMutableArray arrayWithObjects:
                                [NSValue valueWithCGPoint:CGPointMake(1, 1)],
                                [NSValue valueWithCGPoint:CGPointMake(1, 1)],
                                [NSValue valueWithCGPoint:CGPointMake(1, 2)],
                                [NSValue valueWithCGPoint:CGPointMake(1, 3)], nil];
    
    NSArray        *points2 = [NSArray arrayWithObject:
                                [NSValue valueWithCGPoint:CGPointMake(1, 1)]];
    
    NSInteger index = NSNotFound;
    
    for (NSValue *point in points2) {
        index = [points1 indexOfObject:point];
    
        if (NSNotFound != index) {
            [points1 removeObjectAtIndex:index];
        }
    }
    
    NSLog(@"%@", points1);
    
    => 2012-03-04 00:02:26.376 foobar[19053:f803] (
           "NSPoint: {1, 1}",
           "NSPoint: {1, 2}",
           "NSPoint: {1, 3}"
       )
    

    更新

    NSNotFoundNSObjCRuntime.h 中定义。你可以通过命令 + 点击 Xcode 中的符号 NSNotFound 来找到它。

    定义是

     enum {NSNotFound = NSIntegerMax};
    

    我知道使用它的原因是查看 NSArray 文档中的 indexOfObject: 方法,内容如下:

    返回值
    对应数组值等于 anObject 的最低索引。如果数组中没有一个对象等于anObject,则返回NSNotFound

    【讨论】:

    • 这很好用,谢谢!你能评论一下 NSNotFound 到底在做什么吗?读完之后,我想我明白发生了什么,但对我来说并不是 100% 清楚。再次感谢。
    • @Vanny 我已经添加了一些说明
    • 感谢您非常彻底的回答,非常感谢。我希望我能支持这个答案,但我是新手。
    猜你喜欢
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 2017-09-19
    相关资源
    最近更新 更多