开发者

Objective-C #import Confusion

开发者 https://www.devze.com 2023-04-03 02:42 出处:网络
I am still a bit confused about the #import statement in Objective-C.I have a header file (Common.h) where I holding some constant NSStrings that are used throughout the application.So far I have used

I am still a bit confused about the #import statement in Objective-C. I have a header file (Common.h) where I holding some constant NSStrings that are used throughout the application. So far I have used #import "Common.h" in 2 classes, and I get a build error:

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:

    //
    //  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. 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.

in Common.h

extern NSString *const EX_XML_URL;

in 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. Just make sure Common.m is included in the files that are compiled and linked into your target.


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:

.h

extern NSString * const EX_XML_URL;

.m

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

精彩评论

暂无评论...
验证码 换一张
取 消