在方法之间传递变量



我希望变量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;

一种面向对象的处理方式是缓存结果的类方法:

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

另一种方法是实例变量。例如,dataInizio似乎既是一个实例变量,也是一个属性。

当然,您可以使用全局变量来代替。只需将"int annoInizio"添加到文件顶部,然后将int annoInizio = ...更改为-init中的annoInizio = ...

相关内容

  • 没有找到相关文章

最新更新