NSArray 技巧

作者: 小布走慢点 | 来源:发表于2016-05-06 11:37 被阅读76次

    NSString 拆分成 NSArray

    NSString *_string = @"1,2,3,4,5";
    NSArray  *_arr = [_string componentsSeparatedByString:NSLocalizedString(@",", nil)];
    

    NSArray 转为 NSString

    NSArray  *_arr = [[NSArray alloc] initWithObjects:@"1", @"2", @"3", @"4", @"5", nil];
    NSString *_str = [_arr componentsJoinedByString:@","];
    

    NSArray ,NSSet 互转

    NSArray *arr = @[@"12-11", @"12-11", @"12-11", @"12-12", @"12-13", @"12-14"];  
    NSSet *set = [NSSet setWithArray:arr]; //去重复
    NSArray *sortDesc = @[[[NSSortDescriptor alloc] initWithKey:nil ascending:YES]];  //排序
    NSArray *sortSetArray = [set sortedArrayUsingDescriptors:sortDesc];  
    

    数组中有字典的排序:

    NSMutableArray *myMutableArr = [[NSMutableArray alloc] init];
    NSDictionary *dicOne = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"price",@"2",@"number", nil];
    NSDictionary *dicTWo = [NSDictionary dictionaryWithObjectsAndKeys:@"6",@"price",@"5",@"number", nil];
    NSDictionary *dicThree = [NSDictionary dictionaryWithObjectsAndKeys:@"3",@"price",@"1",@"number", nil];
    NSDictionary *dicFour = [NSDictionary dictionaryWithObjectsAndKeys:@"4",@"price",@"3",@"number", nil];
    [myMutableArr addObject:dicOne];
    [myMutableArr addObject:dicTWo];
    [myMutableArr addObject:dicThree];
    [myMutableArr addObject:dicFour];
    
    NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"price" ascending:YES]];
    [myMutableArr sortUsingDescriptors:sortDescriptors];
    NSLog(@"排序后的数组%@",myMutableArr);
    

    NSArray的字典条件去重

    NSMutableArray *seatA = [NSMutableArray arrayWithArray:dataSource];
    for (NSDictionary * one in dataSource) {
       for (NSDictionary * two in dataSource) {
           if ([one[@"seat"] isEqualToString:two[@"seat"]]&&![one.objectId isEqualToString:two.objectId]&&[seatA containsObject:one]) {
             //1. "seat"去除条件 2.不要去除了自己 3.保留一个
             [seatA removeObject:two];
         }
      }
    }
    

    NSMutableArray 去除特定(倒序)

    NSMutableArray *array = [[NSMutableArray alloc]init];
    [array addObjectsFromArray:@[@"1",@"2",@"3",@"4",@"5"]];
    
    for (NSString * str in array.reverseObjectEnumerator) {
        if ([str isEqualToString:@"3"]||[str isEqualToString:@"4"]) {
            [array removeObject:str];
        }
    }
    NSLog(@"%@",array);
    /*输出
     (
        1,
        2,
        5
     )
     */

    相关文章

      网友评论

        本文标题:NSArray 技巧

        本文链接:https://www.haomeiwen.com/subject/ashjrttx.html