【发布时间】:2013-06-26 18:02:05
【问题描述】:
我尝试在一个类中定义一个 const NSString。
我做了以下事情:
在.h中:
#import <Foundation/Foundation.h>
@interface GlobalDataModel : NSObject
@property (nonatomic, strong) NSMutableDictionary *infoDictionary;
+ (id)sharedDataModel;
extern NSString * const WS_URL;
@end
.m:
#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
因为智能感知中没有 WS_URL。
【问题讨论】:
-
您能否更明确地说明 there 的含义?可以发一下代码吗?
-
@HepaKKes - 我已经用 while 源修改了我的问题。我希望,现在它更清楚了。感谢您的帮助。
-
我已经回复你了,你不能以这种方式访问那个静态变量,尽管你可以通过与你的单例实例关联的只读属性访问那个
URL -
声明
extern NSString * const WS_URL;声明了一个全局 C 符号。在@interface中声明它不会改变它的范围。
标签: objective-c cocoa-touch nsstring constants