Sorting NSArray of NSXMLNodes

Discussion in 'Mac Programming' started by wildwobby, May 25, 2008.

  1. wildwobby macrumors member

    Joined:
    Nov 3, 2007
    #1
    Hi,

    I am making an app that fetches XML data from the internet and put it into a NSTableView. It is like Chapter 28 in the new 'Cocoa Programming for Mac OS X ed. 3' except it used the Digg API instead. The problem is, the NSTableView can't sort the rows. Does anyone have any ideas of how I can make it sortable? What should the Sort Key be for each column be in IB?

    Any help appreciated!
     
  2. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    This page discusses this:
    http://www.cocoadev.com/index.pl?NSTableViewSort

    I guess you're not sorting your own class, but if you were you'd implement:
    Code:
    - (NSComparisonResult)compare:(MyClassName *)
    You might need to extend NSXMLNode and only implement a compare method. I don't know what you'd compare by (stringValue?), but you could do it however you wanted in that method.

    It looks like you'll need to use a NSMutableArray instead of NSArray, so you can perform the sort, or you can run: sortedArrayUsingSelector on the plan NSArray, but you're getting a new NSArray *, it's not sorted in place.

    -Lee
     
  3. wildwobby thread starter macrumors member

    Joined:
    Nov 3, 2007
    #3
    I tried making a category for NSXMLNode with this method:

    Code:
    - (NSComparisonResult)compareDiggCount:(NSXMLNode *)n
    {	
    	NSError *error;
    	NSString *xp = @"@digg";
    	NSArray *nodes = [n nodesForXPath:xp error:&error];
    	if (!nodes){
    		NSAlert *alert = [NSAlert alertWithError:error];
    		[alert runModal];
    		return NSOrderedSame;
    	}
    	if([nodes count] == 0)
    	{
    		return NSOrderedSame;
    	}else{
    		NSLog(@"int val!:%@", [[nodes objectAtIndex:0] stringValue]);
    	}
    	return NSOrderedSame;
    }
    
    However, it is not getting called anyways... In IB for the digg column I put:'compareDiggCount:' for the selector... although I'm still unsure of what to put for sort key..
     
  4. Nutter macrumors 6502

    Joined:
    Mar 31, 2005
    Location:
    London, England
  5. wildwobby thread starter macrumors member

    Joined:
    Nov 3, 2007
    #6
    Im not as focussed on how bad the method is.... I want to fix it so it actually gets called first. What could I be doing wrong?
     
  6. ATG macrumors regular

    Joined:
    Aug 7, 2005
    #7
    Change:
    Code:
    - (NSComparisonResult)compareDiggCount:(NSXMLNode *)n
    to:
    Code:
    - (NSComparisonResult)compare:(NSXMLNode *)n
    Although the previous poster is right, you should be really be using NSSortDescriptor. Also, putting an NSAlert in a compare method is a very bad idea. compare methods get called a lot.
     

Share This Page