싱글 톤 객체는 한 번만 인스턴스화 할 수 있으며 목표 C에서 싱글 톤을 사용하여 공유 리소스에 대한 전역 액세스 권한을 갖습니다. 또한 다음 방법을 사용하여 싱글 톤이 인스턴스화된다는 것을 알고 있습니다.
+ (instancetype)sharedManager
{
static PhotoManager *sharedPhotoManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedPhotoManager = [[[self class] alloc] init];
sharedPhotoManager->_photosArray = [NSMutableArray array];
});
return sharedPhotoManager;
}
하지만 나도 할 수 있어요
PhotoManager *sharedManager = [[PhotoManager alloc] init];
이제 이런 식으로 동일한 싱글 톤 클래스의 다른 인스턴스를 만들 수도 있습니다. 그러면 두 개의 인스턴스가있는 경우 클래스가 싱글 톤이됩니다.
명확히하십시오.
init
이러한 트릭 을 사용 하여 호출을 금지 할 수 있습니다 - (instancetype)init NS_UNAVAILABLE;
. 싱글 톤 인터페이스에 정의를 추가 하십시오.
[[PhotoManager alloc] init];
사용 대신[[[self class] alloc] init];
PhotoManager *sharedManager = [[PhotoManager alloc] init];
컴파일되지 않습니다.
내 예가 있습니다.
@interface SomeSingleton : NSObject
+ (instancetype)sharedInstance;
- (instancetype)init NS_UNAVAILABLE;
@end
@implementation SomeSingleton
+ (instancetype)sharedInstance {
static dispatch_once_t onceToken;
static SomeSingleton *instance;
dispatch_once(&onceToken, ^{
instance = [[[self class] alloc] init];
});
return instance;
}
- (instancetype)init {
self = [super init];
return self;
}
@end
결과적으로 SomeSingleton *s1 = [SomeSingleton sharedInstance];
작동하지만 SomeSingleton *s2 = [[SomeSingleton alloc] init];
컴파일 오류가 발생합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다