只允许分离有限类型的对象

时间:2018-09-07 04:30:44

标签: ios objective-c sorting

当前,我混合使用不同货币的对象:

ngOnDestroy

和我的代码将这些对象分成各自不同的数组,结果将是:

<div id="bannerdiv">YourDiv</div>

$('#YourDivID').css({
'max-width' : 'YourWidthForDiv',
 'max-height' : 'YourHeightForDiv' 
});

问题是我只想将USD和PHP分开,而其他货币应放入一个数组中。像这样:

NSArray *currencies = @[ @"USD",@"USD",@"USD",@"USD", @"EUR",@"EUR",@"EUR",@"EUR", @"PHP",@"PHP",@"PHP",@"PHP", @"AUD",@"AUD",@"AUD",@"AUD"];

我当前的代码是这样

USD[] = [USD , USD , USD ,USD]

PHP[] = [PHP , PHP , PHP]

EUR[] = [EUR , EUR , EUR]

AUD[] = [AUD, AUD , AUD].

1 个答案:

答案 0 :(得分:1)

您可以使用NSPredicate使事情变得简单易懂,如下所示:-

NSArray *unFilteredCurrencies = @[ @"USD",@"USD",@"USD",@"USD", @"EUR",@"EUR",@"EUR",@"EUR", @"PHP",@"PHP",@"PHP",@"PHP", @"AUD",@"AUD",@"AUD",@"AUD" ];

NSString  * kUsd = @"USD";
NSString  * kPhp = @"PHP";

NSArray *usd    = [unFilteredCurrencies filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(SELF == %@)",kUsd]];
NSArray *php    = [unFilteredCurrencies filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(SELF == %@)",kPhp]];
NSArray *ohters = [unFilteredCurrencies filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(SELF != %@ && SELF != %@)",kUsd,kPhp]];

或者要了解更多信息,或者您想要自己的解决方案,可以创建一个类似:-

的函数
-(NSMutableDictionary *)updateDictionary:(NSMutableDictionary *)dictionary value:(NSString *)value forKey:(NSString *)key{
    if (dictionary[key]) {
        NSMutableArray *addedCurrencies =dictionary[key];
        [addedCurrencies addObject:value];
        dictionary[key] = addedCurrencies;
    }else{
        NSMutableArray *addCurrency = @[value].mutableCopy;
        dictionary[key] = addCurrency ;
    }
    return dictionary;
}

并在您的方法中调用它,例如:-

NSArray *unFilteredCurrencies = @[ @"USD",@"USD",@"USD",@"USD", @"EUR",@"EUR",@"EUR",@"EUR", @"PHP",@"PHP",@"PHP",@"PHP", @"AUD",@"AUD",@"AUD",@"AUD" ];
NSMutableDictionary * filteredCurrencies = [NSMutableDictionary new];
NSString  * kUsd = @"USD";
NSString  * kPhp = @"PHP";
NSString  * kOther = @"Other";
for (NSString *string in unFilteredCurrencies){
    if ([string isEqualToString:kUsd]){
        filteredCurrencies = [self updateDictionary:filteredCurrencies value:string forKey:kUsd];
    }else if([string isEqualToString:kPhp]){
        filteredCurrencies = [self updateDictionary:filteredCurrencies value:string forKey:kPhp];
    }else{
        filteredCurrencies = [self updateDictionary:filteredCurrencies value:string forKey:kOther];
    }
}