2011-12-01 72 views
2

我有這樣的代碼:如何找到兩次之間的區別?

-(IBAction)startTime:(id)sender { 
    NSDate *myDateTime1 = [[NSDate alloc] init]; 
    NSLog(@"%@", myDateTime1); 
    [myDateTime1 release]; 
} 

-(IBAction)stopTime:(id)sender { 
    NSDate *myDateTime2 = [[NSDate alloc] init]; 
    NSLog(@"%@", myDateTime2); 
    [myDateTime2 release]; 
} 

我想找到兩個時間之間的區別。我怎樣才能做到這一點?

回答

6

你需要做的日期高德。目前他們不知道彼此的存在。

MyClass.m(更換MyClass的用於無論你的類叫做)

@interface MyClass() 

@property (nonatomic, retain) NSDate *startDate; // Add an ivar to hold the startDate 

@end 

@implementation MyClass 

@synthesize startDate = _startDate; 

// More of your class 

- (void)dealloc; 
{ 
    [_startDate release]; 
    // release anything else 
    [super dealloc]; 
} 

-(IBAction)startTime:(id)sender 
{ 
    self.startDate = [NSDate date]; 
} 

- (IBAction)stopTime:(id)sender 
{ 
    NSDate *endDate = [NSDate date]; 

    NSLog(@"%f", [endDate timeIntervalSinceDate:self.startDate]); 
} 

// More of your class 

@end 
+0

+1起草它完全脫離了 – Till

+0

我認爲的NSLog的 'SELD' 必須是 '自我'。我不能編輯它,因爲它少於六個字符。 – santobedi

+1

@santobedi歡呼聲 - 我已更正了錯字。 –

3

用途:

- (NSTimeInterval)timeIntervalSinceReferenceDate 

NSTimeInterval timeDifference = [self.stopTime timeIntervalSinceReferenceDate: self.startTime]; 

更簡單地使用一個方便的方法,不需要發佈:

-(IBAction)startTime:(id)sender { 
    NSLog(@"%@", [NSDate date]); 
} 
相關問題