何时和何处放置@class声明 [英] when and where to put @class declarations

查看:119
本文介绍了何时和何处放置@class声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个具有多个自定义类的项目。我有一个 CardModel (NSObject)有一些整数属性来保存数据,和一个 Deck 一个包含 CardModels 和一个 CardView (UIView) CardModel 作为我从 Deck 中选择 CardModel 时创建的属性。然后我有一堆 UIViewControllers ,我在 UINavigationController 上移动。

I am working on a project with several custom classes. I have a CardModel (NSObject) that has some integer properties to hold data, and a Deck (NSObject) that has an array to hold a bunch of CardModels and then a CardView (UIView) that has a CardModel as a property that I make when I select a CardModel from a Deck. And then I've got a bunch of UIViewControllers that I move around on a UINavigationController.

我的问题是关于使用 @class 编译器指令的位置和时间。

My question is about where and when to use the @class compiler directive.

如果我通过创建一个新文件并子类化一个 UIViewController ,我应该使用 @class MyViewController MyViewController.h .m 的标题,并放在实际使用控制器的文件头(就像一个控制器要实例化另一个控制器类型并将其推送到堆栈)。或者我需要使用它吗?它只是需要,如果我实际上添加新的属性到我的类超出了股票实现中的什么?看起来我把 @class 放在整个地方,只是确保我不会得到错误,但是我根本不理解当我需要它。

If I subclass a UIViewController by making a new file and subclassing it, should I use the @class MyViewController in the header of MyViewController.h or .m and does it go in the header of the file that actually uses the controller (like when one controller is going to instantiate another controller type and push it to the stack). Or do I need to use it at all? Is it only required if I actually add new properties to my class beyond what's in the stock implementation? It seems like I'm putting @class all over the place just make sure I don't get errors but I don't fundamentally understand when I need it.

谢谢!

推荐答案

示例:
两个自定义类:Car和Wheel

Example: Two custom classes: Car and Wheel

Car.h
----------------
@interface Car : NSObject {
}
- (void)addWheel:(Wheel*)newWheel;
@end

Car.h不知道类'Wheel'会抛出一个错误,所以你可以导入W​​heel.h像这样:

Car.h doesn't know about the class 'Wheel' so it would throw an error so you could import the Wheel.h like so:

Car.h
----------------
#import "Wheel.h"

@interface Car : NSObject {
}
- (void)addWheel:(Wheel*)newWheel;
@end

但是你也不需要这样做。 Car.h不需要知道Wheel类的任何东西,它只需要知道它存在。所以你使用的是@class,只是说嘿,这个类存在。以我的话。

BUT you dont need to do this either. Car.h doesn't need to know anything about the Wheel class, it just needs to know it exists. So what you use is the @class to just say that "Hey, this class exists. Take my word for it."

Car.h
----------------
@class Wheel;

@interface Car : NSObject {
}
- (void)addWheel:(Wheel*)newWheel;
@end

然后在Car.m里面,当你真的需要知道Wheel类(属性,方法等),你应该导入Wheel.h。

Then inside of the Car.m, when you actually need to know about the Wheel class (properties, methods, etc) you should import the Wheel.h there.

这篇关于何时和何处放置@class声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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