카테고리 없음

[iOS] 뷰 컨트롤러 / spritekit 장면에서 싱글 톤이 지속되지 않음

행복을전해요 2021. 1. 26. 15:53

싱글 톤 구현 사용을 고려하십시오 .

// ShowSingleton.h

#import <Foundation/Foundation.h>
#import "Show.h"

@interface ShowSingleton : NSObject

+ (instancetype)singleton;

@end

// ShowSingleton.m

#import "ShowSingleton.h"

@implementation ShowSingleton

+ (instancetype)singleton {
   static id sharedInstance = nil;
   
      static dispatch_once_t onceToken;
         dispatch_once(&onceToken, ^{
               sharedInstance = [[self alloc] init];
                  });
                  
                     return sharedInstance;
                     }
                     
                     @end
                     
-------------------

ShowSingleton *shared 클래스가 아닌 메서드로 범위가 지정됩니다.

AppDelegate의 클래스 속성으로 선언 한 다음 다음과 같이 getter를 재정의합니다.

@property (strong, nonatomic) Show *currentShow;

그런 다음 getter를 다음과 같이 재정의하십시오.

+(Show*)currentShow
{
    static id _currentShow = nil;
        static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                    currentShow = [showsarray objectAtIndex:sender.tag]; //probably not this, not sure where in your app flow this info is ready...
                        });
                            return _currentShow;
                            }
                            

이제 Apple이 제공 한 적절한 단일 UIApplicationDelegate를 활용하고 Show다음을 호출하여 앱 어디에서나 액세스 할 수 있는 변하지 않는 인스턴스로 끝낼 수 있습니다.(YourApplicationClass*)[[UIApplication sharedApplication] currentShow]

dispatch_once는 앱 수명주기에 연결되어 있습니다. 앱이 종료 될 때만 제거됩니다. 앱이 백그라운드에있는 동안 일 수 있습니다.

Singleton은 올바르게 구현하기가 까다 롭고 사용이 실제로 정당한시기를 알기가 훨씬 더 어렵 기 때문에 NSUserDefaults대신 목적에 맞게 구부릴 수있는 것이 있는지 살펴볼 수 있습니다.



출처
https://stackoverflow.com/questions/22029777