简体   繁体   中英

Listing the content of an array in alphabetical order

I have an array, with some names (String) in it.

1.) I want to list these names in the array in alphabetical order. 2.) Later i will add some more names to this array, so it had to get appended to this array.

How can i do this programatically ?

note: i don't have any code to demonstrate my working so far. i just have an array created.

EDIT

If my array declaration is ;

NSArray *array = [NSArray arrayWithObjects:@"A",@"C",@"B", @"M",nil];

how can i sort this ?

This will do what you need:

NSArray * sortedArray = [yourArray sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];

Of course, some people might ask why you didn't search the Apple docs for "sort array" before asking the question. Not me though. I'm happy to take the points!

You should really try getting used to looking at documentation - once you get the hang of it you can figure things out pretty quickly

The docs for NSArray give you the exact way to sort an array:

NSArray *array       = [NSArray arrayWithObjects:@"A", @"C", @"B", @"M", nil];
NSArray *sortedArray = [array sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

Now considering you are wanting to add objects later you will most likely use an NSMutableArray the docs for NSMutableArray show the method:

- (void)sortUsingSelector:(SEL)comparator

Therefore you could use

NSMutableArray *myMutableArray = [NSMutableArray arrayWithObjects:@"c", @"a", @"b", nil];
[myMutableArray sortUsingSelector:@selector(caseInsensitiveCompare:)];

which will sort your array in place resulting in

2012-01-10 17:47:11.477 Untitled[11904:707] (
    a,
    b,
    c
)

This requires that you sort the Array (and you would need to do after new values get added to). This is pretty simple to do:

NSArray *sortedArray = [myArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

This example would be case insensitive - but you could do case sensitive as well.

If you want to be able to append later, then you should use the mutable type of either NSArray or NSDictionary . If the array contains only names with no other data associated, then the easiest is to use an NSMutableArray to store them.

To alphabetize, you can use the NSArray method sortedArrayUsingSelector: together with @selector(caseInsensitiveCompare:) . This does all the work for you as efficiently as possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM