开发者

dynamic properties in objective c

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.

Thanks.

Additional info:

  • I only care about -something (getter) working so if your solution does not support setters that is fine.

Example:

@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.

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.

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).


I don't believe this is possible. If you use the id type, you may be able to send undeclared messages, but dot syntax really relies on knowing about your specific accessors.


I haven't tried this, but if you provide a getter and setter, does Xcode still want the @synthesize or @dynamic directive?

So if you property is called something, implement -setSomething: and -something.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜