objective-c - 初学者对 obj-c 中从另一个实例访问一个实例感到困惑

标签 objective-c ios sparrow-framework

我是 Objective-C/ios 的新手,对于如何从另一个实例访问 var/实例有点困惑。我也在使用 Sparrow 框架工作,这可能会让事情更加困惑,但无论如何。

情况是我有一个名为 Game 的类的实例。 在游戏中,我有一个名为scrollContainer的变量,它本身就是一个指向SPSprite类类型实例的指针。

我可以在游戏中使用scrollContainer,显然没有问题,但现在我需要从另一个实例(称为Market)访问scrollContainer,这就是我不确定的地方。

我在 Game.m 中声明(我的术语可能全错)scrollContainer,所以我想我需要做的实际上是在 Game.h 中声明(定义?)它,使用 @property,然后 @synthasize 和那么如果我将 Game.h 包含在 Market.m 中,那么我将能够从 Market.m 内部访问scrollContainer var,但这不起作用,因为它在 Market.m 中给了我一个错误(未声明的标识符)

所以我的下一个想法是这些是我的选择......

首次调用 Market.m 初始化函数时将其传递给 scrollContainer 指针并存储它?

我也有一个正在运行的单例,所以也许我存储了scrollContainer,或者可能在我的单例中存储了一个指向Game.m的指针,并且他们尝试从中访问Market.m中的scrollContainer?

哪一种是最好/最简单的方法?

感谢您的建议!

更新

这是请求的代码片段。

@interface Game : SPSprite
{
  @private 
    float mGameWidth;
    float mGameHeight;
}

- (id)initWithWidth:(float)width height:(float)height;

@property (nonatomic, assign) float gameWidth;
@property (nonatomic, assign) float gameHeight;
@property SPSprite *scrollContainer;

@end

还有一点来自 Market.m

- (void)onCloseMarketButton:(SPEvent *)event
{
    NSLog(@"Close Market Clicked!!");

    [self removeAllMarketButtons];

    [closeMarketButton removeFromParent];

    scrollContainer.visible = YES;//gives error

    [self removeFromParent];

}

我只是想,我是否也必须在 Market.m 中 @synthesize scrollContainer 才能在 Market.m 中使用它?

最佳答案

在您的代码中,您写道:

scrollContainer.visible = YES;//gives error

scrollContainer 是如何初始化或分配的?

您提到:

Pass the scrollContainer pointer to the Market.m init function when it's first called and store it?

是的,这是一个可行的方法。

//Some where in Game.m
Market *market = [[Market alloc]initWithScrollContainer:self.scrollContainer];

//Then in Market.m
-(id)initWithScrollContainer:(SPSprite*)scrollContainer{
    //Do your initialization
}

关于objective-c - 初学者对 obj-c 中从另一个实例访问一个实例感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13110523/

相关文章:

ios - 如何在 GMSMapView 上实现 GMSMarker 拖放?

iphone - 子类化 UIViewController 设计考虑

ios - 如何在 WatchOS 的基于页面的界面中显示警报?

iOS:此进程已超过事件进程断言的最大允许数量

ios - 确保在ARC中重新分配

objective-c - 为什么我的警报显示两次?

ios - 使用 AutoLayout 从 UITableViewCell 中删除 subview

iphone - 一个iOS应用程序可以支持多个推送通知注册吗?

iphone - 将 viewController 移动到窗口的后面