簡體   English   中英

如何在內部使用NSMutableArray訂購NSMutableArray

[英]How to order NSMutableArray with NSMutableArray inside

我需要對一個數組進行排序,其中包含一個數組,如下所示:

 NSMutableArray * array_example = [[NSMutableArray alloc] init];

 [array_example addObject:[NSMutableArray arrayWithObjects:
                            string_1,
                            string_2,
                            string_3,
                            nil]
 ];

我如何通過數組的字段“ string_1”訂購此數組? 知道我該怎么做嗎?

謝謝

對於iOS 4及更高版本,可以使用比較器塊輕松完成此操作:

[array_example sortUsingComparator:^(NSArray *o1, NSArray *o2) {
    return (NSComparisonResult)[[o1 objectAtIndex:0] compare:[o2 objectAtIndex:0]];
}];

如果您對塊的工作方式感興趣,可以查看Apple的《塊實用簡短指南》

如果您希望支持iOS 3.x,則必須使用自定義比較功能:

NSComparisonResult compareArrayFirstElement(NSArray *o1, NSArray *o2) {
    return [[o1 objectAtIndex:0] compare:[o2 objectAtIndex:0]];
}

然后使用:

[array_example sortUsingFunction:compareArrayFirstElement context:nil];

您可以循環數組對象並在每個子數組上調用sortedArrayUsingSelector,然后替換ObjectAtIndex:withObject注入回原始數組

    NSMutableArray * array_example = [[NSMutableArray alloc] init];

    [array_example addObject:[NSMutableArray arrayWithObjects:
                            @"z",
                            @"a",
                            @"ddd",
                            nil]
    ];
    [array_example addObject:[NSMutableArray arrayWithObjects:
                            @"g",
                            @"a",
                            @"p",
                            nil]
    ];
    NSLog(@"Original Array: %@", array_example);

    for(int i = 0; i < [array_example  count] ; i++){
        [array_example replaceObjectAtIndex:i withObject:[[array_example objectAtIndex:i] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]];
        // order sub array
    }
    NSLog(@"Sorted Array: %@", array_example);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM