从数组创建集合,其中包含自定义对象数组

时间:2017-04-20 10:09:55

标签: ios objective-c nsarray

NSMutableArray *arrayDetails = [[NSMutableArray alloc] init];
CustomClass *country1       = [[CustomClass alloc] init];
country1.strCountryName     =  @"USA";
country1.code               =  @"12";
[arrayDetails addObject:country1];

CustomClass *country2       = [[CustomClass alloc] init];
country2.strCountryName     =  @"India";
country2.code               =  @"234";
[arrayDetails addObject:country2];

CustomClass *country4       = [[CustomClass alloc] init];
country4.strCountryName     =  @"UK";
country4.code               =   @"34";
[arrayDetails addObject:country4];

CustomClass *country5       = [[CustomClass alloc] init];
country5.strCountryName     =  @"USA";
country5.code               =  @"12";
[arrayDetails addObject:country5];

CustomClass *country6       = [[CustomClass alloc] init];
country6.strCountryName     =  @"India";
country6.code               =  @"12";
[arrayDetails addObject:country6];

CustomClass *country7       = [[CustomClass alloc] init];
country7.strCountryName     =  @"India";
country7.code               =  @"12";
[arrayDetails addObject:country7];

CustomClass *country8       = [[CustomClass alloc] init];
country8.strCountryName     =  @"USA";
country8.code               =  @"12";
[arrayDetails addObject:country8];

CustomClass *country3       = [[CustomClass alloc] init];
country3.strCountryName     =  @"UK";
country3.code               =  @"12";
[arrayDetails addObject:country3];


CustomClass *country77       = [[CustomClass alloc] init];
country77.strCountryName     =  @"PAK";
country77.code               =  @"12";
[arrayDetails addObject:country3];

我想根据国家名称制作单独的集合,所有在一个数组中包含USA的自定义类对象,数组中的India和英国的一个数组,甚至是单个对象PAK。 数据来自服务器,基于我想要创建组的strContry名称。

1 个答案:

答案 0 :(得分:0)

将所有对象添加到“arraydetails”后,请尝试以下代码以实现相同目的。

NSArray *countryNames = [[NSOrderedSet orderedSetWithArray:[arrayDetails valueForKey:@"strCountryName"]] array];
    for (int i =0; i < [countryNames count]; i++) {
        NSMutableArray *countryArray = [[NSMutableArray alloc] init];
        for (CustomClass *country in arrayDetails) {
            if ([country.strCountryName isEqualToString:[countryNames objectAtIndex:i]]) {
                [countryArray addObject:country];
            }
        }
        NSLog(@"Country array[%d] is %@", i, countryArray);
    }