协议中的Objective-C常数 [英] Objective-C constants in protocol

查看:56
本文介绍了协议中的Objective-C常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Objective-C项目中,我有一个像这样的协议:

In my objective-c project, I have a protocol like this:

@protocol MyProtocol

-(id) get:(NSString *) key;

-(void) set:(NSString *) key withValue:(id) value;

-(NSValue *) getSize;

-(void) setSize:(NSValue *) value;

-(NSValue *) getBounds;

-(void) setBounds:(NSValue *) value;

@end

OBJC_EXPORT const NSString *MYPROTOCOL_SIZE;
OBJC_EXPORT const NSString *MYPROTOCOL_BOUNDS;

基本上,那些特定的方法( getSize getBounds setSize setBounds )被认为是值应该分别存储在 MYPROTOCOL_SIZE MYPROTOCOL_BOUNDS 中.

And basically, those specific methods (getSize, getBounds, setSize, setBounds) are supposed the value that is supposed to be stored in MYPROTOCOL_SIZE and MYPROTOCOL_BOUNDS, respectively.

但是,我无法通过串联其他方法的结果来找到设置那些常量字符串的有效方法,因为它给我一个错误:尝试设置它们时, initializer元素不是常量直接地.有没有一种方法可以保证对象将始终被初始化.(例如,在类 load 方法中),而无需在程序运行时手动调用代码?

However, I cannot find an effective way to set those constant strings, by concatenating the results of other methods, because it gives me the error: initializer element is not constant when I try to set them directly. Is there a way I can guarantee that the objects will always be initialized. (e.g. in a classes load method), without having to manually call code when my program runs?

推荐答案

首先,您应该学习命名约定,对于具有访问权限的访问者-(Type);和-(void)set:(Type)value;而您的情况则是:-(Type)get;和-(void)set:(Type)value;

Well first of all, you should learn the naming convention, for accessors you have - (Type); and - (void)set:(Type)value; whereas in your case you did: - (Type)get; and - (void)set:(Type)value;

我建议您也将@property用于您的大小并限制访问器.

I advise you to use @property for your size and bounds accessors too.

现在关于NSString变量声明中的"const",这没有任何意义.Const适用于其左侧的类型,如果它位于行的开头,则它直接适用于其右侧的标记.因此,您拥有的是一个"const NSString",它没有意义,因为NSString已经是不可变的,并且向const对象发送变异消息不会发出任何警告或错误...

Now about the "const" in the NSString variable declaration, it doesn't make sense. Const applies to the type on its left and in case it is at the beginning of the line it applies to the token directly on its right. So what you have is a "const NSString" which doesn't make sense because NSString is already immutable, and sending mutating messages to a const object doesn't issue any warning or errors...

您真正想要的是"NSString * const",它指出指向您的NSString的指针是常量,您只能在初始化时分配它,然后它就不会改变...

What you actually want is "NSString *const" which states that the pointer to your NSString is constant, you can only assign it at initialization and then it doesn't change...

现在了解协议...您确定要使用自己的协议吗?而不是将您的2个NSString作为只读访问器的抽象类吗?

Now about the protocol... Are you sure you want a protocol in your case ? And not an abstract class that would have your 2 NSString as readonly accessors ?

这篇关于协议中的Objective-C常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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