【问题标题】:Objects properties not reachable from all classes并非所有类都可以访问对象属性
【发布时间】:2012-07-18 09:32:57
【问题描述】:

我的项目中有 3 个类:HeliController、FlightView 和 ConnectionView。 HeliController 存储一些连接数据,供 FlightView 和 ConnectionView 使用。

在 ConnectionView 和 HeliController 我都有

// Interface
#import "HeliController.h"
@property (retain) HeliController *heliController;

// Implementation
@synthesize HeliController = _HeliController

ConnectionView 负责所有连接方法,因此此类接收我正在与之通信的外围设备。从这里,我发送要存储在 HeliController 中的外围数据(这也是外围类的委托):

// ConnectionView.m
self.heliController = [[HeliController alloc] initWithDelegateAndPeripheral:self peripheral:peripheral]; 
// Self will receive callbacks from HeliController and the connected peripheral is stored in the HeliController

// HeliController.m:
- (id)initWithDelegateAndPeripheral:(id<HeliControllerDelegate>)delegate peripheral:(CBPeripheral *)peripheral{

if([super init]){
    self.peripheral = peripheral;
    self.peripheral.delegate = self;
}
return self;

}

现在我可以通过 ConnectionView 访问外围设备了

self.heliController.peripheral

并看到两者在堆栈上都有地址:

_heliController HeliController *    0x0017f9e0
_peripheral CBPeripheral *  0x0017e570


我还想从 FlightView 获取外围数据。我愿意

self.heliController = [[HeliController alloc] init];

并在调试器中看到 self.heliController 在堆栈上获取地址

_heliController HeliController *    0x0018ac60

但是外围是 nil

_peripheral CBPeripheral *  0x00000000

这是为什么?我忘记了什么?当我不得不重组我的应用程序时出现了这个问题,我无法弄清楚我做错了什么。

【问题讨论】:

  • 对我来说,您似乎使用了不同的init 序列。在 ConnectionView.h 中,初始化序列是 self.heliController = [[HeliController alloc] initWithDelegateAndPeripheral:self peripheral:peripheral];,在 FlightView.m 中,初始化序列是 self.heliController = [[HeliController alloc] init]; 看起来你没有传递相同的参数FlightView.m 的情况与 ConnectionView.m 的情况一样。我说的对吗?
  • 没错,但我认为当第一次初始化在第二次之前完成时我得到了相同的参数,从而使存储的参数可用于 FlightView。我是 Objective-c 的初学者,所以让我失望的更多是我的理解
  • 您创建了 两个不同的实例,其中包含 两个不同的内容。你不能期望来自不同类的相同内容初始化不同的方式。这是 OOP 的要点,您正在创建具有不同内容的对象的不同实例。两个单独的实例之间没有关系。只需检查两个不同的heliController类的指针,它们肯定是相互独立的。
  • 哦,好的。那么有没有一种在不同类之间共享对象的好方法呢?我的意思是,所有类都可以同时编辑对象?听起来很危险,但我认为这会解决我的问题。
  • 只能使用任何对象的一个​​实例,你只需要一件事:实例的指针。您可以通过此指针访问实例及其所有内容。如果您没有更改将这个指针传递给类,您应该为全局类实现单例类模型,您应该编写类的单例版本,在这种情况下,只会创建一个实例当前类(并且永远不会超过一个),并且您可以在代码中的任何位置使用该单个实例。

标签: iphone objective-c init alloc core-bluetooth


【解决方案1】:

当我在这样的视图之间切换时,我的解决方案是将 heliController 对象发送到 FlightView:

- (IBAction)changeViewToFlight:(id)sender {

FlightView *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"FlightViewIdentifier"];

// Make sure the heliController object is passed on to the FlightView
vc.heliController = self.heliController;

[self.navigationController pushViewController:vc animated:YES];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多