gpt4 book ai didi

ios - 从包含 User 类对象的 NSMutableArray 获取基于属性的唯一对象

转载 作者:可可西里 更新时间:2023-11-01 04:56:54 24 4
gpt4 key购买 nike

@interface User : NSManagedObject
@property (nonatomic, retain) NSString * user_name;
@property (nonatomic, retain) NSString * group_id;
@end

NSMutableArray 包含 User 类类型的对象集我想根据属性 user_name 检索唯一对象意思是我想防止重复 user_name


NSMutableArray *arrayBikePartsFiltering = [NSMutableArray new];

arrayAsFoundSubPart = @[@{
                           partid:12,
       name : @"Silencer"
                          },
                          @{
                           partid:11,
       name : @"Gear"
                           },
                          @{
                               partid:13,
       name : @"Break"
                           },
                          @{
                               partid:12,
       name : @“Silencer”
                           },];

        for (BikeParts *subPart in arrayAsFoundSubPart) {
            
            BOOL isFound = NO;
            for (BikeParts *subPartl2 in array BikeParts Filtering) {
                if ([[subPartl2.part_id stringValue] isEqualToString:[subPart.part_id stringValue]]) {
                    isFound = YES;
                    break;
                }
            }
            if (!isFound) {
                [arrayBikePartsFiltering addObject:subPart];
            }
            
        }

根据上面的数组,我只想 partid=12name="silencer" 一次我想要的结果数组:

arrayAsFoundSubPart = @[@{
                           partid:12,
       name : @"Silencer"
                          },
                          @{
                           partid:11,
       name : @"Gear"
                           },
                          @{
                               partid:13,
       name : @"Break"
                           }
                          ];

最佳答案

NSSet 是你所需要的你可以使用 NSOrderedSet 来保持顺序:

NSOrderedSet* set = [[NSOrderedSet alloc] initWithArray:arrayAsFoundSubPart];

这将为您提供一组完全独特的对象;

如果您正在使用自定义类,您应该实现 isEqual 方法来比较对象(例如通过 Id):

- (BOOL)isEqual:(BikeParts*)object {
return ([object isKindOfClass:[BikeParts class]] && [object.name isEqual:self.name]);
}

结果集将包含唯一对象的有序序列。

或者,您可以循环遍历数组并通过 id 将值分配给字典:

NSMutableDictionary* dict = [NSMutableDictionary new];
for (BikeParts *subPart in arrayAsFoundSubPart) {
//if (!dict[subPart.name])
dict[subPart.name] = subPart;
}

结果将在 dict.allValues

已编辑:按名称而不是按 id 过滤

关于ios - 从包含 User 类对象的 NSMutableArray 获取基于属性的唯一对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30662511/

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