Objective-C에서 몇 가지 연습을하고 있는데 연습 중 하나는 BNRItemStore
이라는 개체의 인스턴스를 만드는 것입니다. 사용되는 방법은 sharedStore가 처음 호출 될 때만이 BNRItemStore의 인스턴스가 생성되고 sharedStore가 가리 키도록 설정하는 것이라고 설명에서 다음정적 변수를 덮어 쓰지 않으십니까?
+ (instancetype)sharedStore
{
static BNRItemStore *sharedStore = nil;
if(!sharedStore)
{
sharedStore = [[self alloc] initPrivate];
}
return sharedStore
}
입니다. 후속 호출은 이미 생성 된 호출 만 반환합니다. 그들은 또한 Obj-C에서 정적 변수가 메소드 실행이 끝나면 파기되지 않는다고 설명합니다. 당신이 만든 처음과 BNRItemStore
의 새로운 인스턴스 sharedStore
를 호출 한 후 다시 같은 방법으로 호출 늘 또 다른 새로운 인스턴스를 생성하고 설정 sharedStore
포인터가 새 인스턴스를 가리 키도록 경우에도 그와
는 말했다되고 ? 정적 변수를 사용하는 경우에도 메서드의 첫 번째 줄은 static 포인터를 nil로 설정하여 현재 (존재하는 경우) 포인터를 효과적으로 지울 수 있기 때문에 논리적으로 보입니다. 맞습니까?
편집 :
@implementation BNRItemStore
+ (instancetype)sharedStore
{
static BNRItemStore *sharedStore = nil;
// Do I need to create a sharedStore?
if (!sharedStore)
{
sharedStore = [[self alloc] initPrivate];
}
return sharedStore;
}
// If a programmer calls [[BNRItemStore alloc] init], let him
// know the error of his ways
- (instancetype)init
{
@throw [NSException exceptionWithName:@"Singleton"
reason:@"Use +[BNRItemStore sharedStore]"
userInfo:nil];
return nil;
}
// Here is the real (secret) private initializer
- (instancetype)initPrivate
{
self = [super init];
if(self)
{
_privateItems = [[NSMutableArray alloc] init];
}
return self;
}
init을 사용할 때 아무런 문제가 없습니다. initPrivate를 제거하고 init 만 사용하십시오. 그것은 "사용자"가 호출 할 때 잘 작동합니다. self 대신 _sharedStore를 반환하십시오. 특히 ARC를 사용할 때 이것은 훌륭하게 작동합니다. 그러나 그것은 당신의 질문에 driectly 관련이 없습니다. 이 질문을 확인 –
: http://stackoverflow.com/questions/18724522/trouble-understanding-static-class-in-ios – ayushn21