How to combine sort condition?

Discussion in 'iOS Programming' started by mikezang, Dec 4, 2010.

  1. mikezang, Dec 4, 2010
    Last edited: Dec 4, 2010

    mikezang macrumors 6502a

    Joined:
    May 22, 2010
    Location:
    Tokyo, Japan
    #1
    I have a class with fields startDate(NSDate), market(int) and allDay(BOOL), I sort them as compare methods as below, when I want to sort my array, I called such methods one by one, I think it is not good performance, but I am not sure how to combine them into one method, can you give me some suggestion?
    Code:
    - (NSComparisonResult)compareStartDate:(MarketEvent *)event {
    	return [self.startDate compare:event.startDate]; 
    }
    
    - (NSComparisonResult)compareTime:(MarketEvent *)event {
    	if (self.allDay && !event.allDay) {
    		return NSOrderedAscending;
    	} 
    	else if (!self.allDay && event.allDay) {
    		return NSOrderedDescending;
    	} 
    	else {
    		return NSOrderedSame;
    	}
    }
    
    - (NSComparisonResult)compareMarket:(MarketEvent *)event {
    	if (self.market > event.market) {
    		return NSOrderedAscending;
    	} 
    	else if (self.market < event.market) {
    		return NSOrderedDescending;
    	} 
    	else {
    		return NSOrderedSame;
    	}
    }
    
     
  2. mikezang thread starter macrumors 6502a

    Joined:
    May 22, 2010
    Location:
    Tokyo, Japan
    #2
    I got an idea, I will try it after I wake up, now I need to sleep...
    Code:
    - (NSComparisonResult)compare:(MarketEvent *)event {
        NSComparisonResult ret = [self compareStartDate:event];
    
        if (NSOrderedSame == ret) {
            ret = [self compareTime:event];
    
            if (ret == NSOrderedSame) {
                 ret = [self compareMarket:event];
            }
        }
    
        return ret;
    }
    
     
  3. mikezang thread starter macrumors 6502a

    Joined:
    May 22, 2010
    Location:
    Tokyo, Japan
    #3
    I tried my idea, the result is not the same as original, I have to try others way.
     

Share This Page