【问题标题】:How do I call a class function from within an object within the class?如何从类中的对象中调用类函数?
【发布时间】:2011-06-24 18:36:47
【问题描述】:

基本上,我想在主类持有指针的子类中调用主类的函数。
我知道我可以让主类启动子类并将函数附加到它。但我不希望这样,我希望子类使用它的 init 函数来初始化自己。
有什么方法可以从 someClass 调用 doSomething 吗?
一些显示我想要的基本代码:
在 MainViewController.h 中:

@class SomeClass;

@interface MainViewController : UIViewController {
        SomeObject *someInformation;
        SomeClass *someInstance;
}
@property (nonatomic, strong) SomeClass *someInstance;

-(void)doSomething:(id)sender;
@end

在 MainViewController.m 中:

@implementation MainViewController
@synthesize someInstance;
-(void)doSomething:(id)sender {
    //do something to someInformation
}
@end

在 SomeClass.h 中:

@interface SomeClass : NSObject {
    UIStuff *outstuff;
}
@property (strong, nonatomic) UIStuff *outstuff;
-(void)somethingHappened:(id)sender;
@end

在 SomeClass.m 中

@implementation SomeClass
@synthesize outStuff;
-(IBAction)somethingHappened:(id)sender {
    //call doSomething to the main class that points to this class
}
@end

【问题讨论】:

  • 你能解释清楚吗?你想从哪个类调用什么函数?
  • 我想从 SomeClass 中调用 doSomething。 (将其添加到问题中)

标签: objective-c xcode


【解决方案1】:

你的术语是不稳定的。类不“持有”其他类。在您的情况下,MainViewController 类的实例具有指向 SomeClass 类对象的 指针。我不是迂腐;诸如此类的糟糕术语会让人怀疑人们对基本和重要概念的理解。

也就是说,如果您希望 SomeClass 对象能够向 MainViewController 实例发送消息,SomeClass 对象需要对 MainViewController 对象的引用。从您发布的代码中,不存在这样的参考。您要么需要扩展 SomeClass 接口来存储对 MainViewController 对象的显式引用,要么可以通过委托使用稍微间接的(至少在概念上)的东西。但是,由于您没有提供具体案例的信息,我们的解决方案将缺乏从细节派生的洞察力。

【讨论】:

  • 没错,我不太清楚确切的术语。我会尝试修复它。我想我正在寻找的是你提到的关于向后参考的内容。您能否解释一下如何创建此引用以及我可以用它做什么?
  • 这样做的主要原因是为了整理我的 MainViewController 文件。我不想在一个巨大的类中完成所有的初始化和函数,而是想根据它们的作用将它们分成更小的类。
  • 在 Coleman 建议存储一个引用之后,我设法想出了一个解决这个问题的方法: Add to SomeClass.h @property (strong, nonatomic) MainViewController *mainView; -(void)setMainView:(MainViewController *)thisMainView;添加到 SomeClass.m @synthesize mainView -(void)setMainView:(MainViewController *)thisMainView { mainView = thisMainView;在主类中调用 setMainView 然后你可以在我在这里发布的 someClass 中使用 [mainView doSomething] 因为我还不能自我回答。
猜你喜欢
  • 1970-01-01
  • 2018-10-25
  • 2015-10-17
  • 1970-01-01
  • 2012-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多