如何在iPhone中对NSMutableArray值Aa-Zz进行排序?

时间:2012-06-30 11:22:55

标签: iphone ios sorting nsmutablearray

我正在尝试在iPhone应用程序中按Aa-Zz格式对NSMutablArray值进行排序。我在我的项目中使用了以下代码。

for (id key in [dictionary allKeys])
        {
            id value = [dictionary valueForKey:key];
            [duplicateArray addObject:value];
            [value release];
            value =nil;
            NSSortDescriptor *sortdis = [[[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES] autorelease];
            NSArray *discriptor = [NSArray arrayWithObjects:sortdis,nil];
            mutableArray = [[duplicateArray sortedArrayUsingDescriptors:discriptor]retain];
        }   
        NSLog(@"mutableArray : %@", mutableArray);
[mutableArray sortUsingSelector:@selector(caseInsensitiveCompare:)];

此错误日志导致应用崩溃:[__NSArrayI sortUsingSelector:]: unrecognized selector sent to instance.

但是,我已经搜索并找到了崩溃的原因。我的mutableArray值是这样的,

(
        {
        Id = 00001;
        Name = "ABCD";
    },
        {
        Id = 00002;
        Name = "BCDE";
    },
        {
        Id = 00003;
        Name = "ZXYS";
    },
        {
        Id = 00004;
        Name = "abcd";
    },
        {
        Id = 00009;
        Name = "bcde";
    },
)

我想对这个数组进行排序,如 ABCD,abcd,BCDE,bcde,ZXYs 。 任何人都可以帮助解决这个问题。

2 个答案:

答案 0 :(得分:1)

戈皮纳特。请在项目中使用此更新代码。

    for (id key in [dictionary allKeys])
    {
        id value = [dictionary valueForKey:key];
        [duplicateArray addObject:value];
        [value release];
        value =nil;
        NSSortDescriptor *sortdis = [[[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]autorelease];
        NSArray *discriptor = [NSArray arrayWithObjects:sortdis,nil];
        mutableArray = [[duplicateArray sortedArrayUsingDescriptors:discriptor]retain];
    }   
    NSLog(@"mutableArray : %@", mutableArray);

我希望它会对你有所帮助。感谢。

答案 1 :(得分:0)

    for (id key in [dictionary allKeys])
    {
        id value = [dictionary valueForKey:key];
        [duplicateArray addObject:value];
    }   
    NSSortDescriptor *sortdis = [[[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]autorelease];
    NSArray *discriptor = [NSArray arrayWithObjects:sortdis,nil];
    NSArray* notAMutableArray = [[duplicateArray sortedArrayUsingDescriptors:discriptor]retain];
    NSLog(@"notAMutableArray : %@", notAMutableArray);

我没有运行这个,但它是一个更好的开始...