나는 아이폰 OS에 5 싱글을 다소 새로운 오전 여기에 설명 된대로 싱글을 사용하고이 같은내 싱글 톤을 개선 할 수 있습니까?
뭔가 :
MyManager.h
#import <Foundation/Foundation.h>
@interface MyManager : NSObject
//Data for section 1
@property(nonatomic,copy) NSString * section1a;
@property(nonatomic, assign) NSUInteger section1b;
//Data for section 2
@property(nonatomic,copy) NSString * section2a;
@property(nonatomic, assign) NSUInteger section2b;
+ (id)sharedInstance;
@end
MyManager.m
을@implementation MyManager
@synthesize section1a, section1b, section2a; , section2b;
+ (id)sharedInstance
{
static dispatch_once_t pred = 0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init]; // or some other init method
});
return _sharedObject;
}
@end
그래서 다음과 같이 사용합니다 :
MyManager * myManager = [MyManager sharedInstance];
myManager.data = self.data
일반적으로 싱글 톤을 어떻게 사용합니까? 내가 놓친 게 있니? 기본 질문에 대해 유감스럽게 생각합니다. 제대로하고 있는지 확인하고 싶습니다. 당신이 ALLOC/초기화 방법이 클래스의 여러 인스턴스를 만들 수 있기 때문에
감사
iOS 5 또는 다른 버전의 차이점을 모르겠습니다. 하지만 당신이 .m 파일에서 이것을 선언했다고 생각합니다 : static MyManager * _sharedObject = nil; –
당신은 단지 당신의 싱글 톤 클래스 ('+ sharedInstance' 메소드를 제외하고)'+ allocWithZone :'과'+ copyWithZone :'에이 두 메소드를 구현할 것이고'static MyManager * _sharedObject; '멤버를 추가 할 수 있습니다 너의 수업에도. :) – holex