Advertise Mobile SDKs Books Events Forum News Social Networking Support Us
Follow @iphonedevsdk on Twitter

Interface 2, Advanced iOS
Mockup & Code Gen
($9.99)

Make your own iPhone apps
and run them live!
(free)

Pic Frame Dynamo: Photo Editing
($0.99)

Abiliator
($1.99)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum > iPhone SDK Development Forums > iPhone SDK Tutorials

Reply
 
LinkBack Thread Tools Display Modes
Old 03-29-2011, 06:27 AM   #1 (permalink)
Cocoa Junkie
 
Duncan C's Avatar
 
Join Date: Dec 2008
Location: Northern Virginia
Posts: 6,005
Duncan C has a spectacular aura about
Default Sorting arrays of objects

Lots of times people ask about how to sort arrays of objects. Here is a brief tutorial on how to go about it

The NSMutableArray class supports quite a few different ways of sorting an array. The tools are quite powerful, and actually pretty easy to use once you get the hang of it.

Here is a brief description of most of them:
  • sortUsingFunction uses a C function pointer.
  • sortUsingDescriptors takes an array of NSSortDescriptor objects. This option lets you sort a list using multiple keys (by last name, and by first name within last name, or sales transactions by sale-person's name, and then by date of transaction within a sales person. )
  • sortUsingComparator sorts an array using a new iOS 4 NSComparator block.
  • sortUsingSelector works if you are sorting an array of objects that have a comparison method. (like NSStrings or NSArrays.)


If you're just sorting an array of NSNumbers, you can sort them with 1 call:

[arrayToSort sortUsingSelector: @selector(compare];

That works because the objects in the array (NSNumber objects) implement the compare method. You could do the same thing for NSString objects, or even for an array of custom data objects that implement a compare method.

Here's some example code using comparator blocks. It sorts an array of dictionaries where each dictionary includes a number in a key "sort_key".

Code:
#define SORT_KEY @"sort_key"

[anArray sortUsingComparator: 
 ^(id obj1, id obj2) 
  {
	  NSInteger value1 = [[obj1 objectForKey: SORT_KEY] intValue];
	  NSInteger value2 = [[obj2 objectForKey: SORT_KEY] intValue];
	  if (value1 > value2) 
    {
      return (NSComparisonResult)NSOrderedDescending;
	  }
	 
	  if (value1 < value2) 
    {
      return (NSComparisonResult)NSOrderedAscending;
	  }
	    return (NSComparisonResult)NSOrderedSame;
  }];

The code above goes through the work of getting an integer value for each sort key and comparing them, as an illustration of how to do it. Since NSNumber objects implement a compare method, it could be rewritten much more simply:

Code:
#define SORT_KEY @"sort_key"

[anArray sortUsingComparator: 
 ^(id obj1, id obj2) 
  {
	  NSNumber* key1 = [obj1 objectForKey: SORT_KEY];
	  NSNumber* key2 = [obj2 objectForKey: SORT_KEY];
	  return [key1 compare: key2];
  }];
or the body of the comparator could even be distilled down to 1 line:

Code:
	  return [[obj1 objectForKey: SORT_KEY] compare: [obj2 objectForKey: SORT_KEY]];
I tend to prefer simple statements and lots of temporary variables because the code is easier to read, and easier to debug. The compiler optimizes away the temporary variables anyway, so there is no advantage to the all-in-one-line version.


For completeness, here is an example of sortUsingFunction:


Code:
[anArray sortUsingFunction: compareObjects context: NULL];
That code requires that you have a global sort function like the one below

Code:
#define SORT_KEY @"sort_key"
NSInteger compareObjects(id obj1, id obj2, void *context)
{
	  NSNumber* key1 = [obj1 objectForKey: SORT_KEY];
	  NSNumber* key2 = [obj2 objectForKey: SORT_KEY];
	  return [key1 compare: key2];
}

NSString includes a wide range of comparison methods that let you specify case sensitive or non case sensitive searching, comparing or ignoring diacritical marks, comparing string representations of numbers, etc. You can use those comparison methods as part of most of the sorting approaches outlined above.
__________________
Regards,

Duncan C
WareTo

Check out our apps in the Apple App store


Check out this password generator app that shows various techniques including using a data container singleton object to share data between objects in your project.

See this tutorial on using UIView animations and layer animations:

See this thread on generating random, non-repeating text

Check out a very cool Macintosh Kaleidoscopes app called ScopeWorks that we released to the Mac App store.
Duncan C is offline   Reply With Quote
Old 01-18-2012, 02:33 AM   #2 (permalink)
Registered Member
 
Join Date: Jan 2012
Posts: 6
jonwizard is on a distinguished road
Default

Hi, Duncan.

I am trying to use an MSMutableArray withObjectsAndKeys but seem to be having a problem getting specific data from just one of my 11 cells to a specific outlet. Here's my post:

http://www.iphonedevsdk.com/forum/ip...tml#post402445

If you have any advice, I'd be very thankful for your help!
jonwizard is offline   Reply With Quote
Old 01-24-2012, 08:37 PM   #3 (permalink)
Intermediate Developer
 
iRanjha's Avatar
 
Join Date: Apr 2010
Location: Earth
Posts: 136
iRanjha is on a distinguished road
Default

What about ABC order?
__________________
Check Out My Apps On The App Store!

SpeedyText 2.0 - FREE!
GSMCounter - FREE!
GSMCounter Pro - $0.99!

Check out my website at: http://ranjhaapplications.com

Need to contact me? Try this link: isaranjha@me.com
iRanjha is offline   Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is On
Trackbacks are On
Pingbacks are On
Refbacks are On



» Advertisements
» Online Users: 478
15 members and 463 guests
alexeir, David-T, Dj_kades, foslock, HemiMG, iAppDeveloper, jeroenkeij, LunarMoon, Mijator, Pauluz85, pipposanta, QuantumDoja, robsmy, sacha1996, usernametaken
Most users ever online was 1,387, 04-10-2012 at 04:21 AM.
» Stats
Members: 175,679
Threads: 94,129
Posts: 402,928
Top Poster: BrianSlick (7,990)
Welcome to our newest member, xzoonxoom
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 09:23 AM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0