2010-05-13 46 views
1

我有一些方法可以返回兩個給定日期之間的平日數。由於調用這些方法在兩個日期分開幾年後調用非常昂貴,我想知道如何以更有效的方式重構這些方法。 返回的結果是正確的,但我覺得iphone處理器正在努力跟上,並因此凍結了應用程序,當我將這些方法稱爲10年。 有什麼建議嗎?在給定時間段內發現平日的性能問題

//daysList contains all weekdays that need to be found between the two dates 
    -(NSInteger) numberOfWeekdaysFromDaysList:(NSMutableArray*) daysList 
               startingFromDate:(NSDate*)startDate 
               toDate:(NSDate*)endDate 
    { 
    NSInteger retNumdays = 0; 

    for (Day *dayObject in [daysList objectEnumerator]) 
    { 
     if ([dayObject isChecked]) 
     { 
     retNumdays += [self numberOfWeekday:[dayObject weekdayNr] startingFromDate:startDate toDate:endDate]; 
     } 
    } 

    return retNumdays; 
    } 


    -(NSInteger) numberOfWeekday:(NSInteger)day 
           startingFromDate:(NSDate*)startDate 
           toDate:(NSDate*)endDate 
    { 
    NSInteger numWeekdays = 0; 
    NSDate *nextDate = startDate; 

    NSComparisonResult result = [endDate compare:nextDate]; 

    //Do while nextDate is in the past 
    while (result == NSOrderedDescending || result == NSOrderedSame) 
    { 
     if ([NSDate weekdayFromDate:nextDate] == day) 
     { 
     numWeekdays++; 
     } 

     nextDate = [nextDate dateByAddingDays:1]; 
     result = [endDate compare:nextDate]; 
    } 

    return numWeekdays; 
    } 

回答

0

您需要創建一個公式來計算週日數,而不是每天循環並計算它們。

像這樣的東西(這是一個粗略的估計),其中startJD和endJD是Julian Dates

​​

當然,這是接近,但不是精確的,因爲它沒有考慮到星期幾它開始並結束。但是這是一般的想法,你需要一個公式,而不是一個循環。

你也可以在this topic by searching找到相當多的東西。

0

爲什麼不看看處理日期的核心基礎類?

CFAbsoluteTimeGetDayOfWeek 返回一個整數,表示由指定的絕對時間指示的星期幾。

SINT32 CFAbsoluteTimeGetDayOfWeek( CFAbsoluteTime在, CFTimeZoneRef TZ );

參數 at:轉換的絕對時間。 tz:用於時間校正的時區。爲GMT傳遞NULL。

返回值: 表示由at指定的星期幾的整數(1-7)。根據ISO-8601,星期一由1表示,星期二由2表示,以此類推。

供貨情況 適用於iOS 2.0及更高版本。 http://developer.apple.com/library/ios/#documentation/CoreFoundation/Conceptual/CFDatesAndTimes/

: 宣佈 CFDate.h

更多可以被發現在