如何根据其他数组的对象从数组中删除对象

时间:2015-09-23 13:47:20

标签: ios objective-c

我想从array中移除name中可以在array2中找到if键的值的每个对象。我已经尝试了循环,但不幸的是我的实现没有用,else NSArray *array = @[ @{ @"type" : @"2", @"name" : @"apple" }, @{ @"type" : @"1", @"name" : @"peanut" }, @{ @"type" : @"3", @"name" : @"orange" }, @{ @"type" : @"1", @"name" : @"cheese" }, ]; NSArray *array2 = @[ @{ @"type" : @"2", @"name" : @"apple" }, @{ @"type" : @"1", @"name" : @"cheese" }, @{ @"type" : @"3", @"name" : @"orange" }, ]; // new array from array and array2, that contains the unique objects from array NSArray *newArray = @[ @{ @"type" : @"1", @"name" : @"peanut" }, ]; 语句记录了每个对象。

这就是我想要实现的目标:

NSMutableArray *newArray = [self.array1 mutableCopy];

for (PFObject * object in newArray) {

    PFObject *placeholderObject = object;

    for (PFObject *object2 in self.array2) {

        if ([placeholderObject[@"name"] isEqualToString:object2[@"name"]]) {

            [self.array1 removeObject:object];

            NSLog (@"EXISTING OBJECT FOUND %@", object);
        } else {


            NSLog(@"UNIQUE OBJECT FOUND %@", idO[@"hirCime"]);

        }


    }


} 

我不确定这是一个好方法,所以如果有人能够展示如何使用任何不同的技术来做这件事,我会非常高兴。如果它必须使用可变或正常的数组并不重要,我只是先用可变的方法尝试它。

这是我们尝试过的:

// first build fragment part
String fragmentWithQueryParams = UriComponentsBuilder.fromPath("/fragment1").queryParam("test","toto").toUriString();

// then generate full path
String fullPath = UriComponentsBuilder.fromPath("/app").fragment(fragmentWithQueryParams).toUriString());

System.out.println(fullPath); // -> "/app#/fragment1?test=toto"

2 个答案:

答案 0 :(得分:2)

如果你愿意,可以通过删除元素来实现这一点,但是你必须确保在迭代它时不改变数组。这是一个例子(基于NSDictionary而不是PFObject ......但类似的逻辑):

NSMutableArray *newArray = [array1 mutableCopy];
for (NSDictionary * object in array1) {
    NSDictionary *placeholderObject = object;
    for (NSDictionary *object2 in array2) {
        if ([placeholderObject[@"name"] isEqualToString:object2[@"name"]]) {
            [newArray removeObject:object];
            NSLog (@"EXISTING OBJECT FOUND %@", object);
            break;
        } else {
            NSLog(@"UNIQUE OBJECT FOUND %@", object);
        }
    }
}

答案 1 :(得分:2)

NSMutableArray *arr = [NSMutableArray arrayWithArray:array];
for (NSDictionary *objDic1 in array) {
    for (NSDictionary *objDic2 in array2) {
        if ([objDic1[@"name"] isEqualToString:objDic2[@"name"]]) {
            [arr removeObject:objDic1];
        }
    }
}
NSArray *resultArr = (NSArray*)arr;