I'm developing an iPhone app, and I'm kinda new to Objective-C and also the class.h and class.m structure.
我正在开发一个iPhone应用程序,我对Objective-C以及class.h和class.m结构都不熟悉。
Now, I have two classes that both need to have a variable of the other one's type. But it just seems impossible.
现在,我有两个类都需要拥有另一个类型的变量。但这似乎是不可能的。
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.
如果在class1.m(或class2.m)中我包含class1.h,然后是class2.h,我不能在class1.h中声明class2变量,如果我包含class2.h然后class1.h,我可以' t在class2.h中声明class1变量。
Hope you got my idea, because this is driving me nuts. Is it really impossible to accomplish this?
希望你有我的想法,因为这让我疯了。这样做真的不可能吗?
Thanks.
谢谢。
2 个解决方案
#1
20
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.
您可以使用@class关键字在头文件中转发声明一个类。这使您可以使用类名来定义实例变量,而无需#import头文件。
Class1.h
Class1.h
@class Class2;
@interface Class1
{
Class2 * class2_instance;
}
...
@end
Class2.h
Class2.h
@class Class1;
@interface Class2
{
Class1 * class1_instance;
}
...
@end
Note that you will still have to #import
the appropriate header file in your .m files
请注意,您仍然需要在.m文件中#import相应的头文件
#2
3
A circular dependency is often an indication of a design problem. Probably one or both of the classes have too many responsibilities. A refactoring that can emerge from a circular dependency is moving the interdependent functionality into its own class that the two original classes both consume.
循环依赖通常表示设计问题。可能一个或两个类都有太多的责任。可以从循环依赖中出现的重构是将相互依赖的功能移动到两个原始类都消耗的自己的类中。
Can you describe the functionality that each class requires from the other?
你能描述一下每个类需要的功能吗?
#1
20
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.
您可以使用@class关键字在头文件中转发声明一个类。这使您可以使用类名来定义实例变量,而无需#import头文件。
Class1.h
Class1.h
@class Class2;
@interface Class1
{
Class2 * class2_instance;
}
...
@end
Class2.h
Class2.h
@class Class1;
@interface Class2
{
Class1 * class1_instance;
}
...
@end
Note that you will still have to #import
the appropriate header file in your .m files
请注意,您仍然需要在.m文件中#import相应的头文件
#2
3
A circular dependency is often an indication of a design problem. Probably one or both of the classes have too many responsibilities. A refactoring that can emerge from a circular dependency is moving the interdependent functionality into its own class that the two original classes both consume.
循环依赖通常表示设计问题。可能一个或两个类都有太多的责任。可以从循环依赖中出现的重构是将相互依赖的功能移动到两个原始类都消耗的自己的类中。
Can you describe the functionality that each class requires from the other?
你能描述一下每个类需要的功能吗?