如何连接视图控制器到NSObject类文件



我想连接并传递动作从ViewController到NSObject类文件。在我的视图控制器中,有UISwitch Button如果我切换,我想在NSObject类文件中工作。

当开关从视图控制器(UIView)打开时,动作必须在NSObject类文件中工作。

我在用Objective-C编程。

这是我的ViewController。m,我只在ViewController文件中这样做。未连接到NSOBject类文件。

- (void)viewDidLoad{
[super viewDidLoad];
//UISwitch work at viewDidload
[self.mySwitch addTarget:self
                  action:@selector(stateChanged:) forControlEvents:UIControlEventValueChanged]; }

- (void)stateChanged:(UISwitch *)switchState{
NSLog(@"current calendar: %@", [[NSCalendar currentCalendar] calendarIdentifier]);
//get the date today
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setCalendar:[NSCalendar currentCalendar]];
NSString *dateToday = [formatter stringFromDate:[NSDate date]];
NSLog(@"Today Date is: %@", [NSDate date]);
self.myLabel.text=dateToday;
if ([switchState isOn]) {
    //[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US@calendar=japanese"]];
    [formatter setCalendar:[[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierJapanese]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSString *dateToday = [formatter stringFromDate:[NSDate date]];
    UILabel *dtDate = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320.0f, 20.0f)];
    [dtDate setText:dateToday];
    self.myLabel.text =dateToday;
    NSString *locale = [[NSLocale currentLocale] localeIdentifier];
    NSLog(@"current date is: %@", dateToday);
    NSLog(@"current locale: %@", locale);
} else {
    //[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [formatter setCalendar:[NSCalendar autoupdatingCurrentCalendar]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSString *dateToday = [formatter stringFromDate:[NSDate date]];
    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320.0f, 20.0f)];
    [myLabel setText:dateToday];
    self.myLabel.text =dateToday;
    //        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //        [formatter setDateStyle:NSDateFormatterMediumStyle];
    NSString *locale = [[NSLocale currentLocale] localeIdentifier];
    NSLog(@"current locale: %@", locale);
    NSLog(@"%@", [formatter stringFromDate: [NSDate date]]);
   }
}

如果你只需要一个动作,那么使用类方法,或者在NSObject扩展类中创建一个全局变量或通知观察者,当你从交换机获得回调时。

- (void)callback:(id)sender
 {
     [MyObject switchState:sender.state];
 }

最新更新