Objective-C:如何访问其他类中的方法 [英] Objective-C: How to access methods in other classes

查看:71
本文介绍了Objective-C:如何访问其他类中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所知道的是一个简单的问题,但是在书籍和Internet上进行了大量搜索之后,我似乎无法提出解决方案.我有一个标准的iPhone项目,其中包含一个ViewController.此时我的应用程序运行正常.

I have what I know is a simple question, but after many searches in books and on the Internet, I can't seem to come up with a solution. I have a standard iPhone project that contains, among other things, a ViewController. My app works just fine at this point.

我现在想创建一个通用类(扩展NSObject),该类将具有一些基本的实用程序方法.我们将此类称为Util.m(以及关联的.h文件).

I now want to create a generic class (extending NSObject) that will have some basic utility methods. Let's call this class Util.m (along with the associated .h file).

我在项目中创建Util类(和.h文件),现在我想从ViewController访问该类类中包含的方法.

I create the Util class (and .h file) in my project, and now I want to access the methods contained in that class class from my ViewController.

这是一个简单版本的Util.h的示例

Here's an example of a simple version of Util.h

#import <Foundation/Foundation.h>

@interface Util : NSObject {

}

- (void)myMethod;

@end

然后,Util.m文件将如下所示:

Then the Util.m file would look something like this:

#import "Util.h"

@implementation Util

- (void)myMethod {
    NSLog(@"myMethod Called");
}

@end

现在,我的Util类已创建,我想从我的ViewController调用"myMethod"方法.在ViewController的.h文件中,执行以下操作:

Now that my Util class is created, I want to call the "myMethod" method from my ViewController. In my ViewController's .h file, I do the following:

#import "Util.h"

@interface MyViewController : UIViewController {

    Util *utils;

}

@property (assign) Util *utils;

@end

最后,在ViewController.m中,执行以下操作:

Finally, in the ViewController.m, I do the following:

#import "Util.h"

@implementation MyViewController

@synthesize utils;

- (void)viewDidLoad {
    [super viewDidLoad];

    utils.myMethod;  //this doesn't work
    [utils myMethod]; //this doesn't work either
    NSLog(@"utils = %@", utils);  //in the console, this prints "utils = (null)"
}

我做错了什么?我不仅希望能够在像这样的简单util类中直接引用其他类/方法,而且还希望直接引用其他ViewController及其属性和方法.

What am I doing wrong? I'd like to not only be able to directly reference other classes/methods in a simple util class like this, but I'd also like to directly reference other ViewControllers and their properties and methods as well.

我很困惑!请帮忙.

推荐答案

您可能应该看一看许多Objective C教程之一,但对您问题的直接回答是您尚未分配并初始化的实例.你的对象.该代码应如下所示:

You should probably take a look at one of the many Objective C tutorials, but the direct answer to your question is that you have not allocated and initialised an instance of your object. The code should look like:

utils = [[Utils alloc] init];
[utils myMethod];

这篇关于Objective-C:如何访问其他类中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆