使用常量NSString作为NSUserDefaults的键 [英] Using a constant NSString as the key for NSUserDefaults

查看:118
本文介绍了使用常量NSString作为NSUserDefaults的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用NSUSerDefaults存储用户首选项。我记得读某处设置键作为常量是一个好主意 - 我同意。以下代码是我目前的代码:

I'm using NSUSerDefaults to store user preferences. I remember reading somewhere that setting the keys as constants is a good idea - and I agree. The following code is what I currently have:

[[NSUserDefaults standardUserDefaults]
        setObject:[NSNumber numberWithInt:polygon.numberOfSides] 
           forKey:@"polygonNumberOfSides"];

我尝试将其更改为:

@implementation Controller

NSString const *kPolygonNumberOfSides = @"polygonNumberOfSides";

-(void)savePolygonInfo {
    [[NSUserDefaults standardUserDefaults]
            setObject:[NSNumber numberWithInt:polygon.numberOfSides] 
               forKey:kPolygonNumberOfSides];
}

这样做会产生警告:传递'objectForKey:'的参数1,丢弃来自指针目标类型的限定符。我希望保持我的代码免于编译器警告。如何解决此警告?

While this does work, it produces "warning: passing argument 1 of 'objectForKey:' discards qualifiers from pointer target type". I'm keen to keep my code free from compiler warnings. How can I fix this warning?

推荐答案

您应该使用:

NSString * const kPolygonNumberOfSides = @"..."; // const pointer

而不是:

NSString const * kPolygonNumberOfSides = @"..."; // pointer to const

第一个是指向NSString对象的常量指针,指向常量NSString对象的指针。

The first is a constant pointer to an NSString object, while the second is a pointer to a constant NSString object.

这是一个微妙的区别。编译器警告发生,因为 setObject:forKey:声明如下:

It is a subtle difference. The compiler warning happens because setObject:forKey: is declared as follows:

- (void)setObject:(id)value forKey:(NSString *)defaultName;

它期望 defaultName NSString * 类型。

更新: 我想指出,如果这些常量只能在单个文件中使用,那么应该定义为 static 。我说这是因为我自己遇到了这个问题:如果你不将它们声明为静态,那么它们将存在于全局命名空间中,并且您将无法在另一个文件中使用具有相同名称的变量。有关详细信息,请参见 Objective-C中的常量 。通过示例来说明,这是我目前用于只需要在一个 .m 文件中使用的键:

Update: I want to point out that these constants should be defined as static if they are only going to be used from within a single file. I say this because I have run across this problem myself: if you do not declare them as static, then they will exist in the global namespace, and you will not be able to use a variable with the same the same name in another file. see Constants in Objective-C for more information. To explain by example, this is what I currently use for keys that I only need to use in one .m file:

static NSString * const kSomeLabel = @"...";

这篇关于使用常量NSString作为NSUserDefaults的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆