[英]Proper Consts in Obj-C
I seem to be having difficulty understanding how to use Class static consts in Objective-C. 我似乎很难理解如何在Objective-C中使用Class静态const。
I come form a PHP background, and really what im trying to do is the equivalent of this: 我来自PHP背景,实际上我想做的就是这样的:
MyObject.php MyObject.php
<?
class MyObject {
const A_VALUE = 1;
const ANOTHER_VALUE = 2;
}
?>
Which can be used like 可以像
MyObject::A_VALUE
and inside the class like 在班级内部
self::A_VALUE
I want to kind of replicate this behaviour in Obj-C, but I understand theres a FAR different syntax. 我想在Obj-C中复制此行为,但我知道这里有一个FAR不同的语法。
in Objective-C 在Objective-C中
I figured it would look something similar to this 我认为它看起来会与此相似
MyObject.h MyObject.h
static int A_VALUE = 1;
static int ANOTHER_VALUE = 2;
@interface MyObject : NSObject;
This TECHNICALLY works, but it throws a GREAT deal of Warnings about unused variables 从技术上讲这是可行的,但是它会引发有关未使用变量的重大警告
HOWEVER 然而
MyObject.h MyObject.h
static NSString *A_VALUE = @"1";
static NSString *ANOTHER_VALUE = @"2";
@interface MyObject : NSObject;
THIS works without error. 这工作没有错误。 Despite not being used anywhere. 尽管没有在任何地方使用。
Well, I dont want to use a large series of strings, not only does this not feel very efficient at all (especially when theres many), but I hate looking at my code nd seeing a bunch of 好吧,我不想使用大量的字符串,这不仅一点也不高效(特别是在有很多字符串的情况下),而且我讨厌看我的代码并看到很多
if( [value isEqualToString:A_VALUE] ) {
Just. 只是。 Gross. 毛。 Could be worse, but eww. 可能会更糟,但是。 I would prefer: 我会比较喜欢:
if( value == A_VALUE ) {
However what i have works for right now, but ive been at a bit of a loss. 但是我现在所做的一切,但是我有点茫然。
What is the proper way in Objective C to make consts (specifically int) 在Objective C中使用const的正确方法是什么(特别是int)
Cheers everyone! 欢呼大家!
You should define your integer constant this way: 您应该这样定义整数常量:
static const NSInteger kYourConstString = 4;
and for your string: 并为您的字符串:
static NSString *const kYourConstString = @"An example";
in your .m file. 在您的.m文件中。 The static
keyword will make the variable scope local to the compilation unit: your .m file. static
关键字将使变量作用域局部于编译单元:.m文件。
或将enum
用于int
,将#define
用于字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.