簡體   English   中英

Objective-C #import Confusion

[英]Objective-C #import Confusion

我對Objective-C中的#import語句仍然有點困惑。 我有一個頭文件(Common.h),其中我持有一些在整個應用程序中使用的常量NSStrings。 到目前為止,我在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聲明為:

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

我的印象是( 從這篇文章中#import防止頭文件被包含兩次。 我在這里錯過了什么?

在標題(.h)文件中,您應該只聲明常量,然后應該定義常量並在實現(.m)文件中指定一個值。

在Common.h中

extern NSString *const EX_XML_URL;

在Common.m

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


如果您在Common.m中唯一擁有的是常量定義,那就沒關系了,如果這就是事情的解決方法。 只需確保Common.m包含在編譯並鏈接到目標的文件中。

您需要將字符串拆分為2個文件,一個在頭文件中聲明它們extern,另一個實際包含文字:

。H

extern NSString * const EX_XML_URL;

.M

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM