我创建了一个类“AppConstant”,并为“baseURL”定义了一个全局常量,如下所示。
APPCostant.h

#import <Foundation/Foundation.h>

extern NSString * const appBaseUrl;

@interface APPConstant : NSObject
@end

` AppConstant.m
#import "APPConstant.h"

@implementation APPConstant

/** defining base url of server **/
NSString *const AppbaseURL = @"http://www.exapmle.com/";

@end

现在,我已经在我的类中导入了AppConstant.h,我想在其中使用基本URL,并尝试按以下方式构建我的URL,但出现编译时错误。

体系结构x86_64的未定义符号:
“_appBaseUrl”,引用自:
-KKSearchViewController.o
中的[KKSearchViewController searchRequest]
 NSURL *url =[NSURL URLWithString:@"search" relativeToURL:[NSURL URLWithString:appBaseUrl]];

我不确定,这是怎么了。我想要实现的是一点更简洁,可重用的代码,这样我就不必在每个类中都更改url。

最佳答案

有两种方法可以实现您所追求的目标,但是不幸的是,您将两种方法混为一谈。

第一种方法是全局变量。第二个是类属性。

在.h文件中,您有一个全局变量,而在.m文件中,您(有一种)具有class属性。

如果要使用全局变量方法,只需从.m文件中删除@implementation:

AppConstant.m

 #import "AppConstant.h"

 NSString * const appBaseUrl = @"http://someserver.com";

然后,您可以像在appBaseUrl调用中一样简单地引用URLWithString

第二种方法是使用类级别的属性。不幸的是,Objective-C没有类级别的属性,因此您必须声明一个返回所需值的类级别的函数。但是,您可以使用.访问器在Objective C中引用0参数方法,因此它看起来像一个类级属性。

AppConstant.h
#import <Foundation/Foundation.h>

@interface AppConstant : NSObject

+(NSString *)appBaseUrl;

@end

AppConstant.m
#import "AppConstant.h"

@implementation AppConstant

+(NSString *)appBaseUrl {
    return(@"http://someserver.com");
}

@end

在这种情况下,您需要使用AppConstant.appBaseUrl的值。

关于ios - 从常量类访问基本URL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37850751/

10-11 14:55