2011-09-07 112 views
4

我仍然對Objective-C中的#import語句感到困惑。我有一個頭文件(Common.h),其中包含一些在整個應用程序中使用的常量NSString。到目前爲止,我在2班使用#import "Common.h",我也得到一個編譯錯誤:Objective-C#import混淆

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聲明如下:

// 
    // 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"; 

我的印象(from this post)根據該#import後衛對抗的頭文件被包括兩次。我在這裏想念什麼?

+1

''import''可以防止頭文件在同一個實現文件***中包含兩次***。它消除了對C頭文件熟悉的'#IFNDEF'邏輯的需求。 –

回答

6

在你的頭文件(.h),你應該只聲明的常數,那麼你應該定義不斷,並指定在您的實現(.M)文件中的值。

在COMMON.H

在Common.m

extern NSString *const EX_XML_URL; 

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


也沒關係,如果你在Common.m擁有的唯一的事情是不變的定義,如果是這樣的東西的工作方式出。只要確保Common.m包含在已編譯並鏈接到目標文件中。

+0

榮譽,以及對** NSGod **的讚揚,他在我編輯我的答案時發佈了代碼行。幹得好,先生。 –

4

你要字符串分割成2個文件,其中之一的extern聲明它們在頭文件,另一個實際包含文字:

.H

extern NSString * const EX_XML_URL; 

.M

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