简体   繁体   English

来自另一个类的objective-c调用函数

[英]objective-c call function from another class

I have a function on a class "loadingViewController" that needs to be accessed from other classes. 我在类“loadViewController”上有一个函数,需要从其他类访问。 First time that I call function like follows, it works but if I then call it again from another class do not because allocates it again and reset parameters. 我第一次调用函数如下,它可以工作,但如果我再从另一个类调用它不要因为再次分配它并重置参数。 Same if I create an instance method. 如果我创建一个实例方法,则相同。 How to simply call a function from another class without init or allocate again? 如何简单地从另一个类调用一个函数而不用init或再次分配? Probably basic newbie issue... Thanks. 可能是基本的新手问题......谢谢。

class was declared in header and properly synthesized. class在头文件中声明并正确合成。

self.loadingController = [[loadingViewController alloc] initWithNibName:@"loadingViewController" bundle:nil];
[loadingController incrementProgress:0.1];

Hard to say for sure without seeing more code, but I'm thinking you just need to make sure you only initialize the loadingController once: 很难说没有看到更多的代码,但我想你只需要确保你只初始化一次loadingController

if ( self.loadingController == nil ) {
    self.loadingController = [[loadingViewController alloc] initWithNibName:@"loadingViewController" bundle:nil];
}
[self.loadingController incrementProgress:0.1];

You can implement protocols here. 您可以在此处实施protocols Protocols are used to call methods of another class from one class. 协议用于从一个类调用另一个类的方法。 In general it will define the set of methods which your class will implement. 通常,它将定义您的类将实现的方法集。 TO see how to implement it you can see this answer . 要了解如何实现它,您可以看到这个答案

I would do this: 我会这样做:

-(void) loadingViewController
{
    if ( self.loadingController == nil ) {
        self.loadingController = [[loadingViewController alloc] initWithNibName:@"loadingViewController" bundle:nil];
    }
    [self.loadingController incrementProgress:0.1];
}

AND make sure you don't call [xyz loadingViewController] from any other thread than the main UI thread. 并确保不要从主UI线程以外的任何其他线程调用[xyz loadingViewController]。

It looks like the reason you want to call a function on a view controller is to present the progress of a long operation to the user. 看起来您想要在视图控制器上调用函数的原因是向用户呈现长操作的进度。

The more common approach is to have the view controller start the operation and then observe it's progress, updating the view accordingly. 更常见的方法是让视图控制器启动操作,然后观察它的进度,相应地更新视图。

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

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