我无法从NSData类访问位于UIViewController中的所有标签,滑块和开关。

到目前为止,这是我的代码:

FirstViewController.h

@interface FirstViewController : UIViewController
@property (strong) IBOutlet UISwitch * mySwitch;
@property (strong) IBOutlet UISlider *myTransitionSlide;
@property (nonatomic,retain) IBOutlet UILabel *labelTest;


myNSDataClass.h

#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
@class FirstViewController;


@interface myNSDataClass : NSObject <UIApplicationDelegate,CBPeripheralManagerDelegate>
{
    FirstViewController *firstViewController;
}
@property (nonatomic, retain) FirstViewController *firstViewController;


myNSDataClass.m

- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests
{
    self.firstViewController = [[FirstViewController alloc]init];
    [[self.firstViewController labelTest]setText:@"text changed"];
    [self.firstViewController.myTransitionSlide setValue:1];
    [self.firstViewController.mySwitch setOn:NO animated:YES];
}


我知道问题来自FirstViewController的重新分配,但我不知道该怎么办。

最佳答案

您不应从其他任何地方访问出口,而应从拥有出口的视图控制器中访问。另外,您希望将网点设置为weak

要解决您的问题,您可以使用通知:

- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests
{
   [[NSNotificationCenter defaultCenter] postNotificationName:@"MyAppDidReceiveWriteRequestNotification"
                                                       object:nil
                                                     userInfo:@{@"text": @"text changed", @"switchOn": @(NO)}];
}


然后,在您的FirstViewController中,将自己注册为该通知的观察者,例如在viewDidLoad中:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleDidReceiveWriteRequestNotification:)
                                                 name:@"MyAppDidReceiveWriteRequestNotification"
                                               object:nil];

}


然后实现处理程序:

- (void)handleDidReceiveWriteRequestNotification:(NSNotification *)note
{
  [self.labelTest setText:note.userInfo[@"text"]];
  [self.mySwitch setOn:[note.userInfo[@"switchOn"] boolValue] animated:YES];
}


然后您清理:

- (void)dealloc
{
   [[NSNotificationCenter defaultCenter] removeObserver:self];
}


而已。干净得多。

另外,您希望将通知的名称和userInfo字典键的名称转换为常量,以便在代码中的多个位置没有相同的字符串文字。

关于ios - 从NSObject类更改UISwitch的状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22661510/

10-12 16:25