2013-04-19 3 views
0

У меня есть 2 NSMutableArrays, который содержит экземпляры класса Person. Мне нужно проверить, есть ли какое-либо Лицо с одинаковым значением «имя» в обоих массивах и объединить его с вопросом о замене экземпляров Reson одинаковым значением «name».Как сравнить и объединить NSMutableArray

Это выглядит следующим образом:

empl1 = [ 
    Person [ 
     name = @"Paul", 
     age = 45, 
    ], 
    Person [ 
     name = @"John", 
     age = 36, 
    ] 
] 


empl2 = [ 
    Person [ 
     name = @"Paul", 
     age = 47, 
    ], 
    Person [ 
     name = @"Sean", 
     age = 30, 
    ] 
] 

Затем программа спросить о замене лица @ "Пол" в empl1 с Person @ "Пол" в empl2 и добавить новые лица из empl2 в empl2

И результат должен быть (если мы заменим Павла):

empl = [ 
    Person [ 
     name = @"Paul", 
     age = 47, 
    ], 
    Person [ 
     name = @"John", 
     age = 36, 
    ], 
    Person [ 
     name = @"Sean", 
     age = 30, 
    ] 
] 

Подумайте об этом 2 дня, но безуспешно. Пожалуйста, помогите :)

ответ

1

Вы можете реализовать -isEqual: и hash на Лицо и поместить все объекты в Набор.

@interface Person : NSObject 
@property(copy) NSString *name; 
@property NSUInteger age; 
@end 

@implementation Person 

-(BOOL)isEqual:(id)otherPerson 
{ 
    if([otherPerson isKindOfClass:[self class]]) 
     return [self.name isEqual:otherPerson.name]; 
    return false; 
} 

-(NSUInteger)hash 
{ 
    return [self.name hash]; 
} 
@end 

если вы сейчас положить его в NSSet или NSOrderedSet только первый объект с таким же именем будет сохранена. Другой будет обнаружен как дубликат и не будет сохранен в наборе.

Для более: Collections Programming Topics


#import <Foundation/Foundation.h> 
@interface Person : NSObject 
@property(copy) NSString *name; 
@property NSUInteger age; 

-(id)initWithName:(NSString *)name age:(NSUInteger)age; 

@end 

@implementation Person 


-(id)initWithName:(NSString *)name age:(NSUInteger)age 
{ 
    if(self = [super init]) 
    { 
     _name = name; 
     _age = age; 
    } 
    return self; 
} 

-(BOOL)isEqual:(id)otherPerson 
{ 
    if([otherPerson isKindOfClass:[self class]]){ 
     Person *rhsPerson = otherPerson; 
     return [self.name isEqualToString:rhsPerson.name]; 
    } 
    return false; 
} 

-(NSUInteger)hash 
{ 
    return [self.name hash]; 
} 

-(NSString *)description 
{ 
    return [NSString stringWithFormat:@"%@ %lu", self.name, self.age]; 
} 
@end 


int main(int argc, const char * argv[]) 
{ 

    @autoreleasepool { 
     NSArray *p1Array = @[[[Person alloc] initWithName:@"Paul" age:45] , 
          [[Person alloc] initWithName:@"John" age:36]]; 
     NSArray *p2Array = @[[[Person alloc] initWithName:@"Paul" age:47] , 
          [[Person alloc] initWithName:@"Sean" age:30]]; 

     NSMutableSet *resultSet = [[NSMutableSet alloc] initWithArray:p1Array]; 
     NSMutableSet *duplicates = [[NSMutableSet alloc] initWithArray:p2Array]; 
     [duplicates intersectSet:resultSet]; 
     [resultSet addObjectsFromArray:p2Array]; 

     if ([duplicates count]) { 
      for (Person *p in [duplicates allObjects]) { 

       NSMutableSet *interSet = [resultSet mutableCopy]; 
       [interSet intersectSet:[NSSet setWithObject:p]]; 
       Person *pInSet = [interSet allObjects][0]; 

       NSLog(@"%@ <-> %@", p, pInSet); 
       /* 
       Here you have the pairs of duplicated objects. 
       depending on your further requierements, stror them somewhere 
       and process it further after asking the user. 
       */ 
      } 
     } 

    } 
    return 0; 
} 
+1

Или, если вы не хотите, чтобы равенство было строго основано на имени в другом месте, придерживание имен в наборе, чтобы быстро определить, есть ли у вас обман, все равно будет хорошим решением этой проблемы. – Chuck

+0

Этот пример не делает самого важного - предложение заменить или пропустить существующий элемент целевого массива – Maxim

+0

и как он мог? сформируйте свой вопрос, это даже не ясно, если этот код должен работать на Mac, iOS, CLI ... все это будет работать по-другому. – vikingosegundo

Смежные вопросы