按Objective-C中的一个属性对自定义对象的NSSet进行排序

问题描述 投票:0回答:1

我试图通过属性或属性的最常见值对数组进行排序。 This question和其他人建议你可以使用NSSet有效地做到这一点。但是,它只是按最常见的字符串排序,而不是自定义对象中的属性值。我如何获得以下内容以返回最受欢迎的标题?

NSArray<Articles*> *results = [self.managedObjectContext executeFetchRequest:fetchRequest
                                                                error:&error];

    NSCountedSet* mySet = [[NSCountedSet alloc] initWithArray:results];
    Articles* mostRead = nil;
    NSUInteger highestCount = 0;

                for(Articles* article in results) {
                    NSUInteger count = [mySet countForObject:article.title];
                    if(count > highestCount) {
                        highestCount = count;
                        mostRead = article;
                    }
                }

上面的代码没有返回一个值为countForObject:article.title似乎没有被识别。

ios nsarray nsfetchrequest nsset
1个回答
0
投票

你的mySet如果设置为Articles *。然后你算article. title这是NSString *。尝试更改NSString *的设置应该工作。

 NSMutableArray<NSString *> *resultsStr = [NSMutableArray new];
 [results enumerateObjectsUsingBlock:^(Articles * _Nonnull obj,
                                      NSUInteger idx,
                                      BOOL * _Nonnull stop) {
    [resultsStr addObject:obj.title];
 }];
 NSCountedSet* mySet = [[NSCountedSet alloc] initWithArray:resultsStr];
© www.soinside.com 2019 - 2024. All rights reserved.