【问题标题】:Accessing const NSString variable [closed]访问 const NSString 变量
【发布时间】: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


【解决方案1】:

这就是为什么NSString * constNSString 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;
.

【讨论】:

    【解决方案2】:

    你可以像这样使用带有常量的模块:

    常量.h:

    extern NSString * const WS_URL;
    

    常量.m

    #import "Constants.h"   
    
    NSString * const WS_URL = @"blabla";
    

    在 Module.m 中

    #import "Constants.h"
    
    ...
    
    NSString* str = [NSString stringWithFormat: @"blabla=%@", WS_URL];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-12
      • 2020-08-21
      • 1970-01-01
      • 2019-08-22
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      相关资源
      最近更新 更多