问题描述
我正在编写一个iOS应用程序,其中有一个模型类,该模型类将使用提供给它的XMLElement进行初始化.
I'm writing an iOS app in which I have a model class that is going to initialize itself with an XMLElement I give to it.
我正在将TBXML用于XML部分.
I'm using TBXML for the XML part.
模型类的标题如下:
@interface CatalogItem : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSManagedObject *group;
-(id)initWithXMLElement:(TBXMLElement*)element;
@end
现在,我不想包含在其中定义TBXMLElement的标头,而是想在类定义之前用struct TBXMLElement
进行声明.但是,我收到一个预期类型"错误,告诉我我的声明不起作用.这不是我要的吗?
Now instead of including the header in which TBXMLElement is defined, I'd like to forward declare it with: struct TBXMLElement
before the class definition. I'm however getting an "Expected Type" error wich tells me my declaration isn't working. Is this not how I would got about this?
据我了解,将标头文件包含在标头文件中是不好的做法.编译器不需要知道TBXMLElement
的内部工作原理,只需知道它在编译时已存在或将存在.
As I understand it, including header files in header files is bad practice. The compiler doesn't need to know the inner workings of TBXMLElement
, just that it exists or will exist at compile time.
推荐答案
结构的前向声明一直使用,但仍涉及导入标头.这样做的动机是不允许开发人员直接进入该结构. IE.看CFString
.它作为结构实现,但是您不能直接触摸结构内容.取而代之的是,有一个用于处理结构内容的完整API.这样,CFString的实现细节就可以更改,而不会破坏二进制兼容性.
Forward declaration of structs are used all the time, but still involves importing a header. The motivation is to not allow developers to dip into the structure directly. I.e. look at CFString
. It is implemented as a struct, but you can't touch the structure contents directly. Instead, there is a full API for manipulating the struct contents. This allows CFString's implementation details to change without breaking binary compatibility.
在标头中(理想情况下,标头定义了与TBXMLElement*
相关联的任何API):
In your header (ideally the header that defines whatever API is associated with TBXMLElement*
):
TBXMLElement.h:
TBXMLElement.h:
typedef const struct TBLXMLElement *TBXMLElementRef;
extern TBXMLElementRef TBLXMLCreateElement();
... etc ...
然后,在包含TBLXMLElementAPI实现的实现文件中:
Then, in the implementation file containing the implementation of the TBLXMLElementAPI:
TBXMElement.c(假设它是C文件):
TBXMElement.c (assuming it is a C file):
typedef struct __TBLXMLElement {
... struct members here ...
} TBLXMLElement;
TBXMLElementRef TBLXMLCreateElement()
{
return (TBXMLElementRef)malloc(sizeof(TBLXMLElement));
}
... etc ....
这篇关于在目标C中转发声明结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!