@dynamic属性及其用法?

时间:2010-10-28 16:32:51

标签: iphone objective-c properties

有人能给我清楚了解动态属性及其用法吗?你到处都不使用通常的@property?

3 个答案:

答案 0 :(得分:6)

在编译时未提供实现时会使用动态属性,但请确保在运行时存在实现。作为一种动态语言,Objective-C可以在运行时响应消息,即使该类在编译时没有实现。

以下是一个人为的例子:假设您有一个Book类,由NSMutableDictionary支持,其中包含键titleauthor。但是,您希望Book也回复titleauthor,并将其作为属性; titleauthor将从字典中获取适当的值,setTitle:setAuthor:将更改存储在字典中的值。您可以使用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:“创建的”;因此,titleauthor是动态属性。

(这不是最好的例子,但我认为它得到了重点。)

答案 1 :(得分:1)

@dynamic thing;只是一种通知系统不会为thing生成getter / setter的方法,您(或其他人)会为您提供它们 - 就像在,它们将是在那里运行。

这与@synthesize形成对比,后者告诉编译器为你生成getter / setter(视情况而定)。

答案 2 :(得分:1)

@dynamic(根据我的经验)主要与Core Data和NSManagedObject的子类一起使用。引用Marcus Zarra的核心数据,

  

宣布他们   [属性/关系],我们是   告诉编译器忽略任何   与那里相关的警告   属性,因为我们“承诺”   在运行时生成它们。自然,   如果在运行时丢失了,   然后我们的应用程序将   崩溃。