2012-09-11 51 views
0

我嘗試做以下訪問:目標C - 不能在一個方法設定值,並從另一個

1)用戶點擊按鈕開始,它運行startTimer方法,它設置了一個新[NSDate date]

2)用戶點擊按鈕停止它運行stopTimer方法,其中檢索[NSDate date]值。

我無法獲得第2步的工作。我已將其設置在.h文件中。如果我將start方法中的代碼複製到停止方法中,它將起作用。所以,我可以設置[NSDate date]。但是,這不是我想要的。我希望能夠在startTimer方法中設置它。我如何去做這件事?

.h文件中

@interface StartTest : UIViewController { 
    IBOutlet UILabel *timer; 

    NSDate *startNSDate; 
    NSDate *start; 



} 

- (IBAction)startTimer; 
- (IBAction)stopTimer; 

- (NSDate *)setStart; 
- (NSDate *)getStart; 


@end 

.m文件:

@implementation Ash 

- (IBAction)startTimer { 

    startNSDate = [NSDate date]; 

} 


- (IBAction)stopTimer{ 

    start = [NSDate date]; 


    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    [formatter setDateFormat:@"yyyy"]; 


    NSString *stringFromDate = [formatter stringFromDate:startNSDate]; // <<< this is where it fails 

    NSLog(@"stringfromdate: %@", stringFromDate); 
} 
+0

我得到這個錯誤:'主題1:與startTimer線在那裏我有startNSDate – slycat

+0

我可以設置一個varaible(如果它是一個的NSString)與startTimer和stopTimer檢索程序收到信號EXC_BAD_ACCESS' - 我有NSDate有什麼特別的事情嗎? – slycat

+0

爲什麼@ interface和@中的名稱實現不同? – yoninja

回答

2

startNSDate不會保留,由您要訪問它的時候,它已經dealloc'd,因此你試圖訪問垃圾指針

最簡單的解決方案,你將是

@interface StartTest : UIViewController { 
    IBOutlet UILabel *timer; 

    NSDate *startNSDate; 
    NSDate *start; 



} 
@property (nonatomic, strong) NSDate* startNSDate; 

- (IBAction)startTimer; 
- (IBAction)stopTimer; 

- (NSDate *)setStart; 
- (NSDate *)getStart; 


@end 




@implementation Ash 

- (IBAction)startTimer { 

    self.startNSDate = [NSDate date]; 

} 


- (IBAction)stopTimer{ 

    start = [NSDate date]; 


    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    [formatter setDateFormat:@"yyyy"]; 

    // this is where it fails, the reason being that startNSDate isn't retained 
    // and by this line, it's already dealloc'd, hence you're trying to access 
    // garbage pointer 
    NSString *stringFromDate = [formatter self.startNSDate]; 

    NSLog(@"stringfromdate: %@", stringFromDate); 
} 

- (void)dealloc 
{ 
    self.startNSDate = nil; 
    [super dealloc]; 
} 
+0

ahhh,謝謝,我現在就試試:) – slycat

相關問題