Objective-C #import loop

前端 未结 2 1934
星月不相逢
星月不相逢 2020-11-29 06:56

I have the following code:

#import 
#import \"ServerRequest.h\" // works even though this line is included
#import \"ServerRes         


        
相关标签:
2条回答
  • 2020-11-29 07:34

    #import "loops" are not a problem. #import is the same as #include except that it tracks files and makes sure the preprocessor only reads them in the first time.

    Usually when you get an error like that it is due to a problem in the included file. So the error is probably in ServerResponseRecord.h, thought it is probably being tripped by actually using the object declared by it. Without seeing the complete headers it is not possible to say exactly what is going on.

    0 讨论(0)
  • 2020-11-29 07:43

    You've already hinted at the explanation: an #import cycle.

    The first thing I'd do is remove the #include and add the following line above the @protocol definition:

    @class ServerRequest;
    

    This is a forward class declaration, and can help break the import loop. Check out this SO question for more details. Apple also has a brief explanation in this guide.

    Basically, #import'ing a file causes the compiler to bring the entire text of that file into the file in question, and although #import is "smarter" than #include, it doesn't mean you're immune from import errors. The @class declaration is a way to tell the compiler that a class exists without importing the header. It's appropriate to use when you only need to know about the class name, but don't care about the methods it provides. Generally, you want to use @class in the .h file and #import in the .m file, where you're actually interacting with the class.

    0 讨论(0)
提交回复
热议问题