[英]How to find if an object of a class with same data already exists in a NSMutableArray?
對於這個基本問題,我深表歉意,但是我是obj-c的2個月新手。
問題:我無法找到NSMutableArray中是否已經存在具有相同數據的對象。
我在做什么?
ScanDigInfoForTable* sfile = [[ScanDigInfoForTable alloc]init];
sfile.data = "myData";
int inde = [_DataList indexOfObject:sfile] ;
if(inde == -1)
[_DataList addObject:sfile];
ScanDigInfoForTable* sfile2 = [[ScanDigInfoForTable alloc]init];
sfile2.data = "myData";
inde = [_DataList indexOfObject:sfile2] ;
if(inde == -1)
[_DataList addObject:sfile2];
問題: _DataList獲得2個對象而不是1個對象。在此先感謝您的關注。
SP:我已經知道我可以循環遍歷整個數組以檢查數據是否已經存在。 尋找更好的解決方案,因為該陣列可能具有數千條記錄。
在Objective-C中,對象相等性由-isEqual:
和-hash
方法確定。
測試集合中的對象成員資格時, isEqual:
集合中的項目發送isEqual:
默認實現僅比較對象的地址,這就是為什么看到重復的原因。 您的對象不會根據它們包含的數據提供自己的相等性實現。
要解決此問題,您可以覆蓋isEqual:
以根據對象表示的數據比較對象。 使用問題中的示例,可能只是:
- (BOOL) isEqual:(id)object {
BOOL result = N0;
if (object != self){
if ([object isKindOfClass:[self class]]){
result = [[self data] isEqual:[(ScanDigInfoForTable *)object data]];
}
} else {
result = YES;
}
return result;
}
邁克·阿什(Mike Ash)撰寫了一篇有關實現平等的精彩文章。 通常,如果要實現自定義類,則應將平等作為其中的一部分。
好吧,比較兩個自定義對象確實不是那么簡單,因為沒有一個定義相等性的定義方法。 為正在創建的對象定義相等性規則是個人選擇。
在您的情況下,將需要兩個步驟:
步驟1:在您的ScanDigInfoForTable
類中實現isEqual:
。 假設ScanDigInfoForTable
是一個模型類,它有三個字符串屬性- code
, data
和itemID
(你可以有任何類型)。
- (BOOL)isEqual:(ScanDigInfoForTable *)other {
return [self.code isEqualToString:other.code] && [self.data isEqualToString:other.data] && [self.itemID isEqualToString:other.itemID];
}
步驟2:在NSMutableArray
上調用containsObject:
方法。 此方法將在內部調用isEqual:
以根據您定義的規則為您提供結果。
// If the object does not exist in the list, we add it
if (![_DataList containsObject:sfile2]) {
[_DataList addObject:sfile2];
}
例如,您可以使用filteredArrayUsingPredicate
NSArray * matches = [_DataList filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:@"data == %@ ",sfile2.data]];
if(matches.count == 0) {
[_DataList addObject:sfile2];
}
像這樣嗎
NSMutableSet* set1 = [NSMutableSet setWithArray:array1];
NSMutableSet* set2 = [NSMutableSet setWithArray:array2];
[set1 intersectSet:set2]; //this will give you only the obejcts that are in both sets
NSArray* result = [set1 allObjects];
這樣做的好處是,在遍歷另一個具有N ^ 2復雜度的數組時,不查找數組中的對象。
而且set2不必是可變的,不妨只使用
NSSet* set2 = [NSSet setWithArray:array2];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.