[英]Objective C: How do I make an NSMutableSet of NSMutableDictionaries, and have them be unique based on one of the dictionary values?
[英]Objective c - NSMutableSet unique object property
在我的應用程序中,我有一個Person
具有personId
屬性的類。
現在我需要一些數據結構來保存一堆獨特的Person
對象(unique = different personId)
所以我想我應該使用NSMutableSet作為我的數據結構,但是如何讓NSMutableSet在添加一個人時比較personId
屬性(所以我不會添加同一個人多一些)?
我的目標是始終擁有一組獨特的人(即使我添加兩個具有相同ID的人),我希望NSMutableSet能為我做所有艱苦的工作,如果我添加一個已經存在的人它不會添加兩次。
您可以通過了解NSSet
如何進行比較來實現這一目標。 當你向集合中添加一個新對象時,對每個集合的元素調用isEqual:
方法(它是一個NSObject
方法)。 所以你可以做的是覆蓋這個方法並提供這樣的自定義比較:
注意:
如果重寫isEqual:
方法,則必須覆蓋hash
方法
// In your Person.m
- (BOOL)isEqual:(id)anObject
{
return [self.personId isEqual:anObject.personId];
// If it's an object. Otherwise use a simple comparison like self.personId == anObject.personId
}
- (NSUInteger)hash
{
return self.personId; //Must be a unique unsigned integer
}
我想你想要的是一個NSMutableDictionary
,將personId
映射到Person
對象。
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
Person *person = something;
[dict setObject:personObj forKey:[NSNumber numberWithInt:[person personId]]];
... etc ...
(不要忘記稍后在某處釋放dict
)。
為了找到指定personId
的Person
類(比方說12),你可以簡單地做:
Person *person = [dict objectForKey:[NSNumber numberWithInt:12]];
注意:您必須將鍵和值都存儲為對象(不能存儲基本類型)。
在向數組添加項目時,您不必擔心這一點。 只要您每次添加一個唯一對象,對象的屬性就無關緊要了。
如果您對此感到擔心並希望倍加確定,請改用NSMutableSet(除非您需要維護每個對象的順序)。
更新
您可以使用謂詞檢查在添加之前不存在具有相同值的對象。 這對NSMutableArray和NSMutableSet都可以正常工作。
//create array
NSMutableArray *array = [[NSMutableArray alloc] init];
//create person
Person *newPerson = [[Person alloc] init];
//add person
[array addObject:newPerson]
//check new object exists
if([[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"personID == %@", [newPerson personID]]] count] == 0)
{
//add object
[array addObject:newPerson];
}
非常粗糙的偽代碼,但希望你得到的要點:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.