이 개체의 첫 번째 인스턴스를 정적 변수에 저장하고 정적 메서드를 정의하여 해당 개체에 액세스 할 수 있습니다.
static MyViewController *sharedInstance = nil;
@implementation MyViewController
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle
{
... init code here ...
if (!sharedInstance) {
sharedInstance = self;
}
return self;
}
- (id)initWithCoder:(NSCoder *)decoder
{
... init code here ...
if (!sharedInstance) {
sharedInstance = self;
}
return self;
}
+ (MyViewController *)sharedInstance
{
if (!sharedInstance)
[[[self alloc] init] autorelease]; // will be retained inside the init method
return sharedInstance;
}
@end
그런 다음, 다른 곳에서는 앱에 사용하는 변수에 액세스 할 수 있습니다
[MyViewController sharedInsatnce];
그것은 매우 일반적으로 사용되는 패턴하지, 그리고 몇 가지 단점이 있습니다 (예 :이 해제되지 않습니다. 너무 많은 메모리를 사용하지 않도록하십시오.)하지만 UIKit/Foundation의 여러 클래스에서 사용합니다 (NSFileManager, NSUserDefaults, NSBundle 등).
나는 결코 개인적으로 생성하지입니다. 나는 네가 말한 것처럼 스토리 보드를 사용하고있다. 작성한 인스턴스에 액세스 할 수있는 방법이 있습니까? –
불행히도 매우 편리하지는 않습니다. UIApplicateDelegate.window에서 viewcontroller 계층을 하나씩 순회해야합니다. 예 : [self.window.rootViewController.viewControllers objectAtIndex : 0] ApplicationDelegate의 self.window의 루트보기 컨트롤러로 설정된 탭 표시 줄 컨트롤러의 첫 번째 항목에 액세스하는 경우. – barley
아, 나는 제목에서 '초기 viewcontroller'라고 말한 것을 놓쳤습니다. 초기 viewcontroller는 윈도우의 rootviewcontroller이므로 appDelegate.window.rootViewControllerler가 수행합니다. – barley