gpt4 book ai didi

objective-c - 如何比较和合并 NSMutableArray

转载 作者:行者123 更新时间:2023-12-03 17:40:43 26 4
gpt4 key购买 nike

我有 2 个 NSMutableArrays,其中包含 Person 类的实例。我需要检查两个数组中是否有任何具有相同“名称”值的人,并将其与询问是否替换具有相同值“名称”的 Reson 实例合并。

看起来像:

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


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

然后程序询问将 empl1 中的 Person @"Paul"替换为 empl2 中的 Person @"Paul"并将 empl2 中的任何新人员添加到 empl2

结果一定是(如果我们替换 Paul):

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

想了这2天但没有成功。请帮忙:)

最佳答案

您可以在 Person 上实现 -isEqual:hash 并将所有对象放入 Set 中。

@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;
}

关于objective-c - 如何比较和合并 NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16095424/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com