2011-02-17 59 views
1

我有一個非常簡單的java代碼。我不知道如何在Objective C中做到這一點。特別是調用getLocalAddress()方法並將其分配給靜態字符串變量的靜態部分。我知道如何在Objective中設置靜態變量和靜態方法,但我不知道如何在java中實現靜態變量。 在此先感謝...目標C,鏈接錯誤與extern變量

public class Address { 

    public static String localIpAddress; 

    static { 
     localIpAddress = getLocalIpAddress(); 
    } 

    public Address() { 

    } 

    static String getLocalIpAddress() { 
     //do something to get local ip address 
    } 

}

我說這在我的.h文件

#import <Foundation/Foundation.h> 

extern NSString *localIpAddress; 

@class WifiAddrss; 

@interface Address : NSObject { 

} 

@end 

我的.m文件看起來像

#import "Address.h" 
#import "WifiAddress.h" 

@implementation Address 

+(void)initialize{ 
    if(self == [Address class]){ 
     localIpAddress = [self getLocalIpAddress]; 
    } 
} 

+(NSString *)getLocalIpAddress{ 
     return address here 
} 

-(id)init{  
    self = [super init]; 
    if (self == nil){ 
     NSLog(@"init error"); 
    } 

    return self; 
} 
@end 

而且現在我收到一個鏈接錯誤,它抱怨「extern NSString * localIpAddress」部分。如果我將extern更改爲靜態,它可以正常工作。但我想要做的是,我想讓「localIpAddress」變量的範圍變得更爲寬泛。因爲如果我在Objective-C的變量前面放置「static」,那麼該變量僅在類中可見。但是這一次,我想把它作爲一個變量。所以我的問題是,如何讓「localIpAddress」變量作爲grobal變量第一次創建Address類時初始化一次..在此先感謝...

回答

3

你已經宣佈你的.h文件中的變量(告訴編譯器它存在以及它是哪種類型),現在你需要在.m文件中定義它(實際上使它存在)。

只需添加NSString *localIpAddress;到您的.m文件,或者更好的是:

NSString *localIpAddress = nil; 

(也就是說,給它一個理智的默認值)

extern關鍵字的意思是:有的變量給定名稱和類型,但實際上存在於需要鏈接的「外部」文件中。因此,對於每個extern聲明,您需要實際定義一個實現文件中的變量(.c,.cxx/.C++/.cpp,.m;該機制是Objective-C所支持的C標準的一部分)。

+0

非常感謝你!有效!!!!! – codereviewanskquestions 2011-02-17 07:24:24

0

快速解決方法是將localIpAddress變量移動到您的實現文件中。那麼你不需要使用extern關鍵字。真的,如果你考慮一下,你有一個靜態訪問器,所以沒有理由在頭文件中擁有變量聲明本身。

讓我澄清一下:

接口:

#import <Foundation/Foundation.h> 

@interface Address : NSObject { 

} 

+(void) initializeLocalIpAddress; 

+(NSString *) localIpAddress; 

@end 

實現:

#import "Address.h" 
#import "WifiAddress.h" 

NSString *localIpAddress; 

@implementation Address 

+(void) initializeLocalIpAddress 
{ 
    //get the local ip address here 
    localIpAddress = ...; 
} 

+(NSString *) localIpAddress 
{ 
    return localIpAddress; 
} 

-(id)init {  
    if ((self = [super init])) { 
     NSLog(@"init error"); 
    } 
    return self; 
} 
@end 
+0

但是,那麼你不能從其他文件訪問它,所以不是一個修復,恐怕。 – DarkDust 2011-02-17 07:19:35

+0

您可以使用getLocalIpAddress訪問器訪問它。 – LandonSchropp 2011-02-17 07:20:48

1

除非你想其他模塊直接訪問localIpAddress不使用你的類,它聲明爲static裏面你實施(.m)文件。

extern應在以下情況下使用:

  • 模塊變量定義爲全局的。該特定翻譯單元一定不能使用extern
  • 其他模塊需要直接訪問該變量。這些特定的翻譯單元必須使用extern

因爲這不是你的情況,做在你執行以下(.M)文件:

static NSString *localIpAddress; 

// … 

+(NSString *)getLocalIpAddress{ 
    return localIpAddress; 
} 

,並刪除

extern NSString *localIpAddress; 

從你的頭文件(.h)文件中。

每當你需要得到這個地址,使用

NSString *addr = [Address getLocalIpAddress]; 

順便說一句,該公約是getter方法不get啓動。例如,你可以命名該方法localIpAddress