2012-04-25 115 views
0

我希望變量annoInizio和annoFine在mostrarisultato方法中可用。我能怎麼做?我嘗試了不同的解決方案,但是我不能。我想我服務於代碼中任何地方使用的全局變量。在方法之間傳遞變量

- (id)init { 
    if (self == [super init]) { 
     NSDate *adesso = [NSDate date]; 
     NSDateComponents *adessoComponents = [[NSCalendar currentCalendar] components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:adesso]; 
     //NSDate *dopo = [NSDate date]; 
     NSDateComponents *dopoComponents = [[NSCalendar currentCalendar] components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:adesso]; 


     NSDate *oggiAMezzanotte = [[NSCalendar currentCalendar] dateFromComponents:adessoComponents]; 
     NSDate *oggifinito = [[NSCalendar currentCalendar] dateFromComponents:dopoComponents]; 
     //[datePicker setDateValue:oggiAMezzanotte]; 
     //[datePicker2 setDateValue:oggiAMezzanotte]; 

     int daysToAdd = 364; 
     NSDate *newDate1 = [oggifinito dateByAddingTimeInterval:60*60*24*daysToAdd]; 
     self.dataInizio = oggiAMezzanotte; 
     int annoInizio = [adessoComponents year]; 
     NSLog(@"Anno inizio %i.", annoInizio); 
     self.dataFine = newDate1;// Sets these to "now" 
     NSDateComponents *newDate1Components = [[NSCalendar currentCalendar] components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:newDate1]; 
     int annoFine = [newDate1Components year]; 
     NSLog(@"Anno fine %i.", annoFine); 
    } 
    return self; 
} 

- (IBAction)mostrarisultato:(id)sender; 
{ 



    if (dataFine<dataInizio) { 
     [NSApp beginSheet:theSheet 
      modalForWindow:(NSWindow *)_window 
      modalDelegate:self 
      didEndSelector:nil 
       contextInfo:nil]; 
    } else { 
     [progressIndicator startAnimation: self]; 
     [textView setString: @""]; 
     int lunedi = 0; 
     int martedi = 0; 
     int mercoledi = 0; 
     int giovedi = 0; 
     int venerdi = 0; 
     int sabato = 0; 
     int domenica = 0; 

回答

1

一個面向對象的方式來處理,這將是一類方法,其高速緩存結果:

+ (int) annoInizio { 
    static int singleton; 
    if (!singleton) { 
     .... 
     singleton = ....; 
    } 
    return singleton; 
} 

另一種方法是一個實例變量。例如dataInizio,似乎既是一個實例變量又是一個屬性。

當然,你可以改用全局變量。只需在文件頂部添加'int annoInizio',並在-init中將int annoInizio = ...更改爲annoInizio = ...即可。