2017-06-13 67 views
0

我正在從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]; 



    } 
} 
+0

答案>> https://stackoverflow.com/questions/10387582/checking-an-array-if-it-contains-an-object-by-a-specific-property-objective-c –

+0

您可以通過使用containsObject.Check進行檢查,下面的鏈接可能對您有用https://stackoverflow.com/a/6299064/5184217 –

回答

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."]) 
// ... 
相關問題