@dynamic属性及其用法? [英] @dynamic properties and its usage?
问题描述
有人能给我清楚了解动态属性及其用法吗?你不是到处都使用通常的@property吗?
Can anyone give me clear picture about dynamic property and its usage? y not use the usual @property everywhere?
推荐答案
当你在编译时没有提供实现时,会使用动态属性,但要确保在运行时存在一个。作为一种动态语言,Objective-C可以在运行时响应消息,即使该类在编译时没有实现。
Dynamic properties are used when you don't provide an implementation at compile time, but ensure that one exists at runtime. Being a dynamic language, Objective-C can respond to messages at runtime, even if the class doesn't have an implementation at compile time.
这是一个人为的例子:让我们看看假设你有一个 Book
类,由 NSMutableDictionary
支持,其中包含键 title
和作者
。但是,您希望预订
以回复标题
和作者
同样,并将它们作为属性; title
和 author
将从字典中获取相应的值, setTitle:
和 setAuthor:
将更改存储在字典中的值。您可以使用此代码执行此操作:
Here's a contrived example: Let's say you have a Book
class, backed by an NSMutableDictionary
that contains the keys title
and author
. However, you want Book
to respond to title
and author
as well, and have them as properties; title
and author
will grab the appropriate value from the dictionary, and setTitle:
and setAuthor:
will change the value stored in the dictionary. You could do so with this code:
#import <Foundation/Foundation.h>
@interface Book : NSObject
{
NSMutableDictionary *data;
}
@property (retain) NSString *title;
@property (retain) NSString *author;
@end
@implementation Book
@dynamic title, author;
- (id)init
{
if ((self = [super init])) {
data = [[NSMutableDictionary alloc] init];
[data setObject:@"Tom Sawyer" forKey:@"title"];
[data setObject:@"Mark Twain" forKey:@"author"];
}
return self;
}
- (void)dealloc
{
[data release];
[super dealloc];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
NSString *sel = NSStringFromSelector(selector);
if ([sel rangeOfString:@"set"].location == 0) {
return [NSMethodSignature signatureWithObjCTypes:"v@:@"];
} else {
return [NSMethodSignature signatureWithObjCTypes:"@@:"];
}
}
- (void)forwardInvocation:(NSInvocation *)invocation
{
NSString *key = NSStringFromSelector([invocation selector]);
if ([key rangeOfString:@"set"].location == 0) {
key = [[key substringWithRange:NSMakeRange(3, [key length]-4)] lowercaseString];
NSString *obj;
[invocation getArgument:&obj atIndex:2];
[data setObject:obj forKey:key];
} else {
NSString *obj = [data objectForKey:key];
[invocation setReturnValue:&obj];
}
}
@end
int main(int argc, char **argv)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Book *book = [[Book alloc] init];
printf("%s is written by %s\n", [book.title UTF8String], [book.author UTF8String]);
book.title = @"1984";
book.author = @"George Orwell";
printf("%s is written by %s\n", [book.title UTF8String], [book.author UTF8String]);
[book release];
[pool release];
return 0;
}
注意方法是在运行时通过 forwardInvocation:
;因此, title
和 author
是动态属性。
Note the the methods are "created" at runtime via forwardInvocation:
; hence, title
and author
are dynamic properties.
(这不是最好的例子,但我认为它得到了重点。)
这篇关于@dynamic属性及其用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!