Programing

@synthesize vs @dynamic, 차이점은 무엇입니까?

crosscheck 2020. 10. 4. 10:29
반응형

@synthesize vs @dynamic, 차이점은 무엇입니까?


을 구현 사이의 차이점은 무엇입니까 @property@dynamic또는 @synthesize?


@synthesize는 속성에 대한 getter 및 setter 메서드를 생성합니다. @dynamic은 컴파일러에게 getter 및 setter 메서드가 클래스 자체가 아니라 다른 곳 (수퍼 클래스와 같이 런타임에 제공됨)에 의해 구현된다는 것을 알려줍니다.

@dynamic의 사용은 예를 들어 NSManagedObject(CoreData)의 하위 클래스와 함께 사용하거나 콘센트로 정의되지 않은 수퍼 클래스에 의해 정의 된 속성에 대한 콘센트를 만들려는 경우입니다.

@dynamic은 접근자를 구현하는 책임을 위임하는데도 사용할 수 있습니다. 클래스 내에서 직접 접근자를 구현하는 경우 일반적으로 @dynamic을 사용하지 않습니다.

슈퍼 클래스 :

@property (nonatomic, retain) NSButton *someButton;
...
@synthesize someButton;

아강:

@property (nonatomic, retain) IBOutlet NSButton *someButton;
...
@dynamic someButton;

한 번 봐 가지고 이 글을 ; "런타임에 제공되는 방법"제목 아래 :

CoreData의 NSManagedObject 클래스에서 사용되는 특정 접근 자와 같은 일부 접근자는 런타임에 동적으로 생성됩니다. 이러한 경우에 속성을 선언하고 사용하고 싶지만 컴파일 타임에 누락 된 메서드에 대한 경고를 피하려면 @synthesize 대신 @dynamic 지시문을 사용할 수 있습니다.

...

@dynamic 지시문을 사용하면 본질적으로 컴파일러에게 "걱정하지 마십시오. 메서드가 진행 중입니다."

반면에 @synthesize지시문은 컴파일 타임에 접근 자 메서드를 생성합니다 ( "합성 접근 자와 사용자 지정 접근 자 혼합"섹션에서 언급했듯이 유연하고 둘 중 하나가 구현 된 경우 메서드를 생성하지 않음).


다른 사람들이 말했듯이 일반적으로 컴파일러가 getter 및 / 또는 설정을 생성하도록 @synthesize를 사용하고 직접 작성하려는 경우 @dynamic을 사용합니다.

아직 언급되지 않은 또 다른 미묘한 점이 있습니다. @synthesize 를 사용하면 getter 또는 setter의 구현을 직접 제공 수 있습니다. 이것은 일부 추가 로직에 대해서만 getter를 구현하고 싶지만 컴파일러가 setter를 생성하도록하는 경우에 유용합니다 (객체의 경우 일반적으로 직접 작성하기가 약간 더 복잡함).

그러나 @ synthesize'd 접근 자에 대한 구현을 작성하는 경우 실제 필드에 의해 뒷받침되어야합니다 (예 : 작성 -(int) getFoo();하는 경우 int foo;필드 가 있어야 함 ). 값이 다른 것에 의해 생성되는 경우 (예 : 다른 필드에서 계산 됨) @dynamic을 사용해야합니다.


@dynamic은 일반적으로 (위에서 언급했듯이) 속성이 런타임에 동적으로 생성 될 때 사용됩니다. NSManagedObject는이를 수행합니다 (모든 속성이 동적 인 이유)-일부 컴파일러 경고를 억제합니다.

속성을 동적으로 생성하는 방법에 대한 좋은 개요 (NSManagedObject 및 CoreData : 없음 : 참조 : http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtDynamicResolution.html#//) apple_ref / doc / uid / TP40008048-CH102-SW1


다음은 @dynamic의 예입니다.

#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;
}

문서에 따라 :

https://developer.apple.com/library/mac/documentation/cocoa/conceptual/ObjCRuntimeGuide/Articles/ocrtDynamicResolution.html

@dynamic은 컴파일러에게 접근 자 메서드가 런타임에 제공됨을 알려줍니다.

With a little bit of investigation I found out that providing accessor methods override the @dynamic directive.

@synthesize tells the compiler to create those accessors for you (getter and setter)

@property tells the compiler that the accessors will be created, and that can be accessed with the dot notation or [object message]


One thing want to add is that if a property is declared as @dynamic it will not occupy memory (I confirmed with allocation instrument). A consequence is that you can declare property in class category.


As per the Apple documentation.

You use the @synthesize statement in a class’s implementation block to tell the compiler to create implementations that match the specification you gave in the @property declaration.

You use the @dynamic statement to tell the compiler to suppress a warning if it can’t find an implementation of accessor methods specified by an @property declaration.

More info:-

https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/DeclaredProperty.html

참고URL : https://stackoverflow.com/questions/1160498/synthesize-vs-dynamic-what-are-the-differences

반응형