目标c的动态特性 [英] dynamic properties in objective c

查看:67
本文介绍了目标c的动态特性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现可以将Objective-C对象属性标记为@dynamic,以使编译器知道实现将在运行时可用.我想知道是否有一种方法可以告诉编译器,对象上的所有属性都是动态的,而无需一一对应地明确指定它们(我之前没有属性列表).我知道如果仅使用[object something]不会有问题,但出于风格目的,我想使用object.something语法.

I found out Objective-C object properties can be marked as @dynamic to let compiler know that implementation will be available at runtime. I'd like to know if there is a way to tell the compiler that all properties on an object are dynamic without explicitly specifying them one-by-one (I don't have a list of properties up front). I know that this would not be a problem if I would just use [object something] but for stylistic purposes I want to use object.something syntax.

我相当确定不可能做到这一点,但我希望有人确认这一点.由于这不是用于生产用途,因此解决方案可以涉及您可以想象的任何事情.

I'm fairly sure that it's not possible to do that but I'd like someone to confirm that. Since this is not for production use solution can involve anything you can imagine.

谢谢.

其他信息:

  • 我只关心-something(getter)的工作,所以如果您的解决方案不支持可以使用setter的话.
  • I only care about -something (getter) working so if your solution does not support setters that is fine.

示例:

@interface MagicalClass : NSObject
// property 'something' is not defined!
@end

@implementation MagicalClass
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { ... }
- (void)forwardInvocation:(NSInvocation *)anInvocation { ... }
@end

MagicalClass *obj = [[MagicalClass alloc] init];
[obj something]; // compiler warning
obj.something; // compiler error

推荐答案

这确实不适用于声明的属性.它们的全部目的是预先声明属性是什么以及如何与它们交互.如果没有要声明的属性,那么就没有任何声明的属性.

This really doesn't work with declared properties. The whole point of them is that you declare upfront what your properties are and how you interact with them. If you don't have any to declare, then you don't have any declared properties.

不幸的是,尽管它比点语法更有效,但它对于普通消息也不能正常工作. Objective-C的静态类型检查将引发一系列的警告,如果任何属性属于非对象类型,则可能无法生成正确的调用代码.

Unfortunately, it also doesn't work well with plain messages, although it can work better than dot syntax. Objective-C's static type checking will throw a hissy-fit of warnings, and if any of the properties are of non-object types, it might not be able to generate the correct calling code.

这种事情在诸如Python和Ruby之类的语言中很常见,在这些语言中不必声明某些东西,但它与Objective-C的配合并不理想.在Objective-C中,访问任意属性通常是通过字符串完成的(请参见键值编码

This kind of thing is common in languages like Python and Ruby where things don't have to be declared, but it just doesn't mesh well with Objective-C. In Objective-C, accessing arbitrary attributes is generally done with strings (cf. Key-Value Coding and NSAttributedString).

这篇关于目标c的动态特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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