如何在Objective-C中的两个类之间引用? [英] How can I have references between two classes in Objective-C?

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

问题描述

我正在开发一个iPhone应用程序,我对Objective-C以及class.h和class.m结构都不熟悉。

I'm developing an iPhone app, and I'm kinda new to Objective-C and also the class.h and class.m structure.

现在,我有两个类都需要有另一个类型的变量。但这似乎是不可能的。

Now, I have two classes that both need to have a variable of the other one's type. But it just seems impossible.

如果在class1.m(或class2.m)中我包含class1.h,然后是class2.h,我不能声明class2 class1.h中的变量,如果我包含class2.h然后是class1.h,我就不能在class2.h中声明class1变量。

If in class1.m (or class2.m) I include class1.h, and then class2.h, I can't declare class2 variables in class1.h, if I include class2.h and then class1.h, I can't declare class1 variables in class2.h.

希望你有我的想法,因为这让我疯了。是否真的无法实现这一目标?

Hope you got my idea, because this is driving me nuts. Is it really impossible to accomplish this?

谢谢。

推荐答案

您可以使用 @class 关键字在头文件中转发声明一个类。这使您可以使用类名来定义实例变量,而无需 #import 头文件。

You can use the @class keyword to forward-declare a class in the header file. This lets you use the class name to define instance variables without having to #import the header file.

Class1.h

@class Class2;

@interface Class1
{
    Class2 * class2_instance;
}
...
@end

Class2.h

@class Class1;

@interface Class2
{
    Class1 * class1_instance;
}
...
@end

请注意仍然必须 #import .m文件中相应的头文件

Note that you will still have to #import the appropriate header file in your .m files

这篇关于如何在Objective-C中的两个类之间引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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