繁体   English   中英

从一个视图控制器获取数据到另一个

[英]getting data from one view controller to another

我正在获取我的蓝牙设备(batteryLevel)的电池电量,这是一个视图中的浮动。 我想将它传递给另一个视图以在文本字段中显示它。

代码在视图中

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:    
    (CBCharacteristic *)characteristic error:(NSError *)error
    {[self.testPeripheral readValueForCharacteristic:mycharacteristic];

    char batlevel;
    [characteristic.value getBytes:&batlevel length:1];
    self.batteryLevel = (float)batlevel;

    NSLog(@"level;%f",batteryLevel);}

这给了我一个像80.00000的值

我想把它放到另一个视图中显示。

我已经在我已经放置的view2.h文件中尝试过了

view1 *t

接着

- (void) batteryIndicatorTimer:(NSTimer *)timer {
    TIBLEUIBatteryBar.progress = t.batteryLevel / 100;
    [t readBattery:[t testPeripheral]];               // Read battery value of keyfob again
    NSLog(@"t.batterylevel:%f",t.batteryLevel);
}

但我没有得到t.batteryLevel的值

我做错了什么,怎么能这样做?

使用委托或在presentationViewControllers / destinationViewControllers中分配属性有很多方法可以实现这一点,但由于我不知道你的应用程序流程,我会给你一种方法,可以使用你所拥有的任何设置。 只需在viewController中更新batteryLevel即peripheralDelegate,然后将值保存到NSUserDefaults:

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:
 (CBCharacteristic *)characteristic error:(NSError *)error
 {
   //Grab your battery value and store in float
   //Then just save to defaults so you can access wherever.. Keep overwriting this value each time you update

   [[NSUserDefaults standardUserDefaults]setFloat:batteryVal forKey:@"battery_level"];

 }

然后在你的另一个viewController里面只是在viewWillAppear里面分配值。

-(void)viewWillAppear:(BOOL)animated
{
    float batteryLevel = [[NSUserDefaults standardUserDefaults]floatForKey:@"battery_level"];
    self.yourTextField.text = [NSString stringWithFormat:@"%f",batteryLevel];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM