[英]Objective C, How to convert this java statment into Objective C code?
我有这样一个非常简单的Java代码。 我不知道如何在目标C中执行此操作。特别是,静态部分调用getLocalAddress()方法并将其分配给静态字符串变量。 我知道如何在Objective中设置静态变量和静态方法,但是我不知道如何在Java中实现static {}部分。 提前致谢...
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更改为static,则可以正常工作。 但是我想做的是使“ localIpAddress”变量的作用域变得怪异。 因为如果在Objective-C中将“静态”放在变量前面,则该变量仅在类中可见。 但是这一次,我想将其作为讨厌的变量。 所以我的问题是如何使“ localIpAddress”变量作为grobal变量,在首次创建Address类时将其初始化一次。
看这里在目标C中模拟Java的静态块:与目标C中的静态构造函数等效吗?
您可以将其实现为类方法,将IP地址存储在static
变量中。
Address.h
@interface Address : NSObject
+ (NSString *)localIPAddress;
@end
Address.m
#import "Address.h"
static NSString *localIPAddress = nil;
@implementation Address
+ (NSString *)localIPAddress {
if (!localIPAddress) {
localIPAddress = @"127.0.0.1";
}
return localIPAddress;
}
@end
发生链接器错误是因为您有一个extern 声明但没有定义 。 要修复特定错误,您需要将.m文件放入类似以下内容的文件:
NSString *localIpAddress = @"some value";
extern
作用是告诉编译器,当链接时间到来时,将有一个名为localIpAddress的变量,即使现在不存在。 .m文件中的上一行在NSString*
的数据段中创建了一些空间,然后将其初始化为指向常量字符串。
对于Objective-C程序,更好的模式是通过类方法公开变量,例如
static localIpAddress; // static limits visibility to this file.
-(void) initialize
{
if (self == [Address class])
{
localIPAddress = /* whatever */;
}
}
+(NSString*) localIpAddress
{
return localIpAddress;
}
或者我更喜欢
+(NSString*) localIpAddress
{
static NSString* localIpAddress = nil;
if (localIpAddress == nil)
{
localIpAddress = /* Do whatever you need to get it */ ;
}
return localIpAddress;
}
听起来您只希望在首次创建实例时创建localIPAddress,而不是通过类方法创建。 这是一个很奇怪的情况,但是请尝试以下操作:
static NSString *localIPAddress = nil;
@implementation Address
- (id)init {
if ((self = [super init])) {
if (!localIPAddress) {
localIPAddress = //getAddress
}
}
return self;
}
@end
当然,这是一个非常不寻常的设置。 通常,您每次创建对象时都会获取本地ip地址,或者使用Jonathan的代码通过类方法来获取它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.