@synthesize를 언제 명시 적으로 사용해야합니까?
내가 아는 한, XCode 4.4 이후로 @synthesize
속성 접근 자를 자동 생성합니다. 그러나 방금에 대한 코드 샘플을 읽었 NSUndoManager
으며 코드에서이 @synthesize
명시 적으로 추가 되었음을 알았습니다 . 처럼:
@interface RootViewController ()
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, strong) NSUndoManager *undoManager;
@end
@implementation RootViewController
//Must explicitly synthesize this
@synthesize undoManager;
지금 당황 스러워요 ... 언제 @synthesize
코드 에 명시 적으로 추가해야 합니까?
많은 답변이 있지만 큰 혼란도 있습니다. 나는 주문을하려고 노력할 것입니다 (또는 엉망진창을 늘리십시오.
Xcode에 대한 이야기는 그만합시다. Xcode는 IDE 입니다. clang은 컴파일러 입니다. 우리가 논의하고있는이 기능 은 속성의 자동 합성 이라고 하며 Xcode에서 사용하는 기본 컴파일러 인 clang 에서 지원 하는 Objective-C 언어 확장 입니다.
명확히하기 위해, Xcode에서 gcc로 전환하면이 기능의 이점을 얻지 못할 것입니다 (Xcode 버전에 관계없이). 같은 방식으로 텍스트 편집기를 사용하고 명령 줄에서 clang을 사용하여 컴파일하는 경우 의지.자동 합성 덕분에 속성을 명시 적으로 합성 할 필요가 없습니다. 컴파일러에 의해 자동으로 합성되므로
@synthesize propertyName = _propertyName
그러나 몇 가지 예외가 있습니다.
사용자 정의 getter 및 setter가있는 readwrite 속성
getter 및 setter 사용자 정의 구현을 모두 제공 할 때 속성이 자동으로 합성되지 않습니다.
사용자 정의 getter가있는 읽기 전용 속성
readonly 속성에 대한 사용자 정의 getter 구현을 제공 할 때 이것은 자동으로 합성되지 않습니다.
@동적
사용하는 경우
@dynamic propertyName
,이 건물은 자동으로 (매우 명백 이후 합성되지 않습니다@dynamic
및@synthesize
상호 배타적입니다)@protocol에 선언 된 속성
프로토콜을 준수 할 때 프로토콜이 정의하는 속성은 자동으로 합성되지 않습니다.
카테고리에 선언 된 속성
이것은
@synthesize
지시문이 컴파일러에 의해 자동으로 삽입되지 않는 경우이지만이 속성도 수동으로 합성 할 수 없습니다. 범주는 속성을 선언 할 수 있지만 범주는 ivar를 만들 수 없으므로 전혀 합성 할 수 없습니다. 완성도 를 위해 Objective-C 런타임을 사용하여 속성 합성을 위조하는 것이 여전히 가능하다는 점 을 덧붙일 것입니다 .재정의 된 속성 (clang-600.0.51 이후 새로운 기능, Xcode 6과 함께 제공됨, Marc Schlüpmann에게 감사드립니다)
슈퍼 클래스의 속성을 재정의 할 때 명시 적으로 합성해야합니다.
속성을 합성하면 백업 ivar가 자동으로 합성되므로 명시 적으로 선언하지 않는 한 속성 합성이 누락 된 경우 ivar도 누락됩니다.
마지막 세 가지 경우를 제외하고 일반적인 철학은 속성에 대한 모든 정보를 수동으로 지정할 때마다 (모든 접근 자 메서드를 구현 @dynamic
하거나을 사용하여 ) 컴파일러가 속성에 대한 모든 권한을 원한다고 가정하고 자동 합성을 비활성화한다는 것입니다. 그것.
위에 나열된 경우를 제외하고 명시 @synthesize
적의 유일한 다른 용도 는 다른 ivar 이름을 지정하는 것입니다. 그러나 규칙이 중요하므로 항상 기본 이름을 사용하는 것이 좋습니다.
명시 적으로 사용하지 않으면 @synthesize
컴파일러는 다음과 같이 작성한 경우 동일한 방식으로 속성을 이해합니다.
@synthesize undoManager=_undoManager;
그러면 다음과 같은 코드를 작성할 수 있습니다.
[_undoManager doSomething]; // iVar
[self.undoManager doSomethingElse]; // Use generated getter
이것은 일반적인 관습입니다.
당신이 쓰면
@synthesize undoManager;
당신은 할 것 :
[undoManager doSomething]; // iVar
[self.undoManager doSomethingElse]; // Use generated getter
@synthesize
더 이상 필수가 아니기 때문에 개인적으로 사용을 중지 합니다. 나를 위해 사용하는 유일한 이유는 @synthesize
을 연결하는 iVar
A를 @property
. 특정 getter 및 setter를 생성하려는 경우. 그러나 주어진 코드에는 아무것도 없습니다. iVar
이것은 @synthesize
쓸모가 없다고 생각합니다 . 하지만 이제 새로운 질문은 "언제 사용해야 iVar
합니까?" 라고 생각합니다.이 질문에 대해서는 "절대"라는 답변이 없습니다!
언제 @synthesize
코드 에 명시 적으로 추가해야 합니까?
일반적으로 필요한 경우 : 필요한 경우에는 결코 맞지 않을 것입니다.
그래도 유용하다고 생각할 수있는 경우가 하나 있습니다.
커스텀 getter와 setter를 모두 작성하고 있지만 인스턴스 변수가이를 지원하고 싶다고 가정 해 보겠습니다. (원자 속성의 경우 이는 사용자 지정 setter를 원하는 것만 큼 간단합니다. 단원 속성에 대해 setter를 지정하면 컴파일러가 getter를 작성하지만 원자 속성은 지정하지 않습니다.)
이걸 고려하세요:
@interface MyObject:NSObject
@property (copy) NSString *title;
@end
@implementation MyObject
- (NSString *)title {
return _title;
}
- (void)setTitle:(NSString *)title {
_title = [title copy];
}
@end
_title
존재하지 않기 때문에 작동하지 않습니다. getter 또는 setter를 모두 지정 했으므로 Xcode가 (올바르게) 이에 대한 백업 인스턴스 변수를 생성하지 않습니다.
두 가지 선택이 있습니다. 다음 중 하나로 변경할 수 있습니다 @implementation
.
@implementation MyObject {
NSString *_title;
}
- (NSString *)title {
return _title;
}
- (void)setTitle:(NSString *)title {
_title = [title copy];
}
@end
또는 다음과 같이 변경하십시오.
@implementation MyObject
@synthesize title = _title;
- (NSString *)title {
return _title;
}
- (void)setTitle:(NSString *)title {
_title = [title copy];
}
@end
In other words, although synthesize is for practical purposes never necessary*, it can be used to define property-backing instance variables when you're providing a getter/setter. You can decide which form here you want to use.
In the past, I've favoured specifying the instance variable in the @implementation {}
, but I now think the @synthesize
route is a better choice as it removes the redundant type and explicitly ties the backing variable to the property:
- Change the property's type, and the instance variable's type changes.
- Change its storage qualifier (for instance, make it weak instead of strong or strong instead of weak) and the storage qualifier changes.
- Remove or rename the property, and the
@synthesize
will generate a compiler error. You won't end up with stray instance variables.
*-I know one case where it was necessary, relating to splitting functionality across categories in multiple files. And I wouldn't be surprised if Apple fixes this, or even already has.
OK, when you create a property...
@property NSString *name;
Xcode will auto synthesise an iVar as if you had written...
@synthesize name = _name;
This means you can access the property with...
self.name;
// or
_name;
Either will work but only self.name
actually uses the accessor methods.
There is only one time that auto synthesise does not work: If you overwrite but the setter AND the getter method then you will need to synthesise the iVar.
You are fine if you just override the setter or if you just override the getter. But if you do both then the compiler won't understand it and you will need to synthesise it manually.
As a rule of thumb though.
Don't make iVars. Just use the property. Don't synthesise it.
Property synthesis is required when a property is declared in a protocol. It will not be automatically synthesized in an implementing interface.
Thanks for clarifying that. I had a similar problem.
@synthesize firstAsset, secondAsset, audioAsset;
@synthesize activityView;
So now, having commented them out, I went through and replaced each occurrence with, for example
self.firstAsset It seems I could also use firstAsset, but I find I miss seeing the "" too often.
Xcode doesn't require an explicit @synthesize
declaration.
If you don't write @synthesize
its the same as doing :
@synthesize manager = _manager;
샘플 코드가 오래되었을 수 있습니다. 곧 업데이트됩니다.
다음과 같은 속성에 액세스 할 수 있습니다.
[self.manager function];
이것은 Apple에서 권장하는 규칙입니다. 나는 그것을 따르고 당신도 그렇게 할 것을 권장합니다!
참고 URL : https://stackoverflow.com/questions/19784454/when-should-i-use-synthesize-explicitly
'code' 카테고리의 다른 글
Dispatcher.Invoke를 사용하여 주 스레드가 아닌 스레드에서 WPF 컨트롤 변경 (0) | 2020.11.03 |
---|---|
iOS UIDevice 방향 감지 (0) | 2020.11.03 |
필터 Android가있는 사용자 정의 Listview 어댑터 (0) | 2020.11.03 |
상대 경로를 사용하여 Webpack에서 SCSS (SASS)를 사용하여 멋진 글꼴을로드하려면 어떻게해야합니까? (0) | 2020.11.03 |
git stash는 분기 별입니까 아니면 전체 저장소입니까? (0) | 2020.11.02 |