如何检查在添加新值之前,数组是否具有相同的对象值

时间:2017-06-13 14:18:00

标签: ios objective-c nsmutablearray

我从Dictionary获取数据。它运行良好并将数据存储在NSMutableArray中我希望在添加对象之前需要确保Array不包含具有相同名称和类型的相同对象。请参阅下文。

在插入对象之前,如果不需要插入,我们应该检查它是否包含带有Type和Name的对象。

NSArray *resultDic = [result1 objectForKey:@"results"];

for (int i = 0; i<[resultDic count]; i++) {
    id item = [resultDic objectAtIndex:i];

    NSDictionary *jsonDict = (NSDictionary *) item;
    GetData  *theObject =[[GetData alloc] init];

    NSString*error = [jsonDict valueForKey:@"error"];
    if(![error isEqualToString:@"No Record Found."])
    {



        [theObject setVaccineID:[jsonDict valueForKey:@"ID"]];
        [theObject setVaccineName:[jsonDict valueForKey:@"Name"]];
        [theObject setVaccinationType:[jsonDict valueForKey:@"Type"]];
        [theObject setVaccineType:[jsonDict valueForKey:@"VType"]];
        [theObject setFarmName:[jsonDict valueForKey:@"FName"]];
        [theObject setDay:[jsonDict valueForKey:@"Day"]];
        [theObject setAddedDateTime:[jsonDict valueForKey:@"DateTime"]];



        [appDelegate.dataArray addObject:theObject];



    }
}

1 个答案:

答案 0 :(得分:1)

通用解决方案是教你的GetData对象如何将自己与其他对象进行比较。如果可以比较它们,那么很容易确定匹配是否在任何集合中(并且您可能也想在其他上下文中比较它们)。通过实施isEqual:来实现这一目标。这可能看起来像这样:

// in GetData.m
- (BOOL)isEqual:(id)object {
    if ([object isKindOfClass:[GetData self]]) {
        // assuming that the object is fully characterized by it's ID
        return [self.vaccineId isEqual:((GetData *)object).vaccineId];
    }
    else {
        return NO;
    }
}

// have the hash value operate on the same characteristics as isEqual
- (NSUInteger)hash {
    return [self.vaccineId hash];
}

完成后,您可以利用NSArray的containsObject:

// ...
if(![appDelegate.dataArray containsObject:theObject] && ![error isEqualToString:@"No Record Found."])
// ...