Objective c 访问常量NSString变量
我试图在类中定义一个常量字符串 我已经做了以下工作: in.h:Objective c 访问常量NSString变量,objective-c,cocoa-touch,nsstring,constants,Objective C,Cocoa Touch,Nsstring,Constants,我试图在类中定义一个常量字符串 我已经做了以下工作: in.h: #import <Foundation/Foundation.h> @interface GlobalDataModel : NSObject @property (nonatomic, strong) NSMutableDictionary *infoDictionary; + (id)sharedDataModel; extern NSString * const WS_URL; @end #impor
#import <Foundation/Foundation.h>
@interface GlobalDataModel : NSObject
@property (nonatomic, strong) NSMutableDictionary *infoDictionary;
+ (id)sharedDataModel;
extern NSString * const WS_URL;
@end
#import "GlobalDataModel.h"
@implementation GlobalDataModel
static GlobalDataModel *sharedInstance = nil;
NSString * const WS_URL = @"http://localhost:57435/IosService.asmx";
- (id)init{
self = [super init];
if (self) {
self.infoDictionary = [NSMutableDictionary dictionary];
}
return self;
}
+ (id )sharedDataModel {
if (nil != sharedInstance) {
return sharedInstance;
}
static dispatch_once_t pred; // Lock
dispatch_once(&pred, ^{ // This code is called at most once per app
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
@end
用法:
#import "GlobalDataModel.h"
GlobalDataModel *model = [GlobalDataModel sharedDataModel];
现在,我可以做了
NSString *temp = model.infoDictionary[@"xxx"];
但不是
NSString *temp = model.WS_URL
因为intellisense中没有WS_URL。这就是为什么
NSString*const
与NSString-const*
是不同的类型,所以编译器会看到您的WS_URL
的重新定义
编辑
如果你认为你,以这种方式声明了一个常数,你可以这样做
#import "GlobalDataModel.h"
.
.
GlobalDataModel *model = [GlobalDataModel new];
model.WS_URL;
.
您错了,这是不可能的:我建议您使用一个只读属性返回该常量
那么,试试这样吧
// GlobalDataModel.m
static NSString * const kURL = @"http://localhost:57435/IosService.asmx";
.
.
- (NSString *)WS_URL
{
return [NSString stringWithString:kURL];
}
// GlobalDataModel.h
.
.
@property (nonatomic, readonly) NSString *WS_URL;
.
您可以将模块与以下常量一起使用: 常数h:
extern NSString * const WS_URL;
常数.m
#import "Constants.h"
NSString * const WS_URL = @"blabla";
在模块m中
#import "Constants.h"
...
NSString* str = [NSString stringWithFormat: @"blabla=%@", WS_URL];
你能更清楚地说明你说的是什么意思吗?你能发布代码吗?@HepaKKes-我已经用while源代码修改了我的问题。我希望,现在更清楚了。谢谢你的帮助。我已经回复过你,你不能用那种方式访问那个静态变量,尽管你可以通过一个与你的单例实例关联的只读属性来访问那个
URL
。声明extern NSString*const WS\u URL代码>声明一个全局C符号。在@接口中声明它不会改变其作用域。