简体   繁体   English

Objective-C #import Confusion

[英]Objective-C #import Confusion

I am still a bit confused about the #import statement in Objective-C. 我对Objective-C中的#import语句仍然有点困惑。 I have a header file (Common.h) where I holding some constant NSStrings that are used throughout the application. 我有一个头文件(Common.h),其中我持有一些在整个应用程序中使用的常量NSStrings。 So far I have used #import "Common.h" in 2 classes, and I get a build error: 到目前为止,我在2个类中使用了#import "Common.h" ,并且出现了构建错误:

duplicate symbol _EX_XML_URL in /Users/username/Library/Developer/Xcode/DerivedData/projectname-ffvcivanbwwtrudifbcjntmoopbo/Build/Intermediates/projectname.build/Debug-iphonesimulator/projectname.build/Objects-normal/i386/NewsView.o and /Users/username/Library/Developer/Xcode/DerivedData/projectname-ffvcivanbwwtrudifbcjntmoopbo/Build/Intermediates/projectname.build/Debug-iphonesimulator/projectname.build/Objects-normal/i386/ViewController.o for architecture i386

EX_XML_URL is declared like: EX_XML_URL声明为:

    //
    //  Common.h
    //  Group of common constants used through out the application

    /*
     *  Constant strings available to application
     */

    #import <Foundation/NSString.h>

    NSString* EX_XML_URL = @"http://myurl.com/xmldata"; // URL for XML data
    NSString* EX_NO_CONNECTION = @"Network not availble";                           
    NSString* EX_DEFAULT_IMAGE = @"logo.png";

I was under the impression ( from this post ) that #import guards against header files being included twice. 我的印象是( 从这篇文章中#import防止头文件被包含两次。 What part am I missing here? 我在这里错过了什么?

In your header (.h) file, you should only declare the constant, and then you should define the constant and assign a value in your implementation (.m) file. 在标题(.h)文件中,您应该只声明常量,然后应该定义常量并在实现(.m)文件中指定一个值。

in Common.h 在Common.h中

extern NSString *const EX_XML_URL;

in Common.m 在Common.m

NSString *const EX_XML_URL = @"http://myurl.com/xmldata";


It's ok if the only thing you have in Common.m is constant definitions, if that's the way things work out. 如果您在Common.m中唯一拥有的是常量定义,那就没关系了,如果这就是事情的解决方法。 Just make sure Common.m is included in the files that are compiled and linked into your target. 只需确保Common.m包含在编译并链接到目标的文件中。

You'll want to split the strings into 2 files, one which declares them extern in the header file, and another that actually contains the literals: 您需要将字符串拆分为2个文件,一个在头文件中声明它们extern,另一个实际包含文字:

.h 。H

extern NSString * const EX_XML_URL;

.m .M

NSString * const EX_XML_URL = @"http://myurl.com/xmldata";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM