2013-02-06 2 views
3

싱글 톤 및 위임에 대한 충분한 정보를 읽었습니다. 그래서, 나는 싱글 톤이 무엇인지 이해하고 있다고 생각합니다. 위임에 관해서 나는 아직도 혼란 스럽다. 저는 위임에 대한 개념을 이해하고 있지만, 위임을 이해하기위한 의정서를 만들어야합니다.싱글 톤 및 위임

좋아, 나는 CoreData에서 내 엔티티와 함께 ​​작업을위한 싱글 톤을 만듭니다. 어쩌면 내가 틀렸고 싱글 톤이 아니 었으니 제발 말해줘. 내 싱글 톤은 FetchData입니다.

Fetchdata.h

#import <Foundation/Foundation.h> 

@interface FetchData : NSObject <UIApplicationDelegate> 

+(FetchData*) fetchData; 

-(NSArray*)fetchLogin:(NSString*)name; 
-(BOOL)newGroup:(NSString*)group forLogin:(NSString*)login; 
-(NSMutableArray*)contactsForGroup:(NSString*)group; 
-(BOOL)newContact:(NSString*)name surname:(NSString*)surname withDatas:(NSArray*)array; 
//other methods 

@end 

Fetchdata.m는

#import "FetchData.h" 
#import "Contact.h" 
#import "Login.h" 
#import "Group.h" 
#import "AppDelegate.h" 

@interface FetchData() 
@property (nonatomic, strong) NSEntityDescription *loginEntity; 
@property (nonatomic, strong) NSEntityDescription* groupEntity; 
@property (nonatomic, strong) NSManagedObjectContext* context; 
@property (nonatomic, strong) NSEntityDescription* contactEntity; 
@property (nonatomic, strong) AppDelegate* appDelegate; 
//other properties 
@end 

@implementation FetchData 
@synthesize //my properties 

+(FetchData*) fetchData 
{ 
static FetchData* fetchData = nil; 
if (!fetchData) 
    fetchData = [[super allocWithZone:nil]init]; 
return fetchData; 
} 

+(id)allocWithZone:(NSZone *)zone 
{ 
return [self fetchData]; 
} 

//implementation my methods 
@end 

그래서, 나를 위해 지금 CoreData와 함께 작동하는 것은 매우 쉽습니다. 난 단지 수입 FetchData이 필요하고 단순히/종류의 추가/변경/삭제/생성하는 방법 ...

SomeClass.m

#import "FetchData.h" 
#define fetching [FetchData fetchData] 

를 사용하지만 난 내 목표 위임에 사용할 수 있다고 생각합니다. 또는 싱글 톤과 비교했을 때 가장 좋은 decesion 일 수 있습니다. 그래서 대표단을 위해 싱글 톤을 다시 만들고 싶습니다. 이 질문에 도움이 필요합니다. 내가 뭘해야하니?

제대로 이해한다면 FetchData.h, FetchData.m의 모든 메소드를 사용하여 프로토콜을 만들어야합니다. 변경하지 않고 그대로 둘 수 있습니다. 그리고 SomeClass에서 FetchData를 가져와 내 프로토콜을 추가해야합니다. 마찬가지로 :

#import <Foundation/Foundation.h> 

@protocol FetchingDelegate 

//all methods from FetchData.h 

@end 

@interface FetchData : NSObject 
@property (nonatomic, strong) id <FetchingDelegate> delegate; 
@end 

FetchData.m

@interface FetchData() 
//all properties without changing 
@end 

@implementation FetchData 
@synthesize //all properties and delegate 

//implementation of methods 
@end 

SomeClass

#import "FetchData.h" 

@interface SomeClass : NSObject <FetchingDelegate> 
@end 

@implementation SomeClass 

-(void)viewDidLoad 
{ 
    FetchData* fetching = [FetchData new] 
    fetching.delegate = self 
} 
//and now I can use any methods from protocol like [fetching anyMethod] 
//such I used with singleton 

답변

9

싱글의 아이디어는 전체 응용 프로그램이 하나의 클래스에 액세스 할 수 있다는 것입니다. 다중 뷰 컨트롤러에는 데이터베이스에서 오는 데이터가 필요할 수 있습니다. 귀하의 경우에는, 당신의 fetchData 방법을 변경 (그리고 정말 지금 규칙을 따르지 않는 아마 이름을 변경) 것 :

+(FetchData*) fetchData 
{ 
    static FetchData *fetchData; 
    dispatch_once_t token; 
    dispatch_once(&token, ^{ 
     if (!fetchData) 
      fetchData = [super init]; 
    } 
return fetchData; 
} 

대표

는 일대일 통신을 의미, 하나의 객체가 가지고있는 의미 위임자는 특정 위임자에게 메시지를 보냅니다.

즉, 싱글 톤과 위임이 서로 잘 어울리지 않는다는 의미입니다. 싱글 톤은 여러 수신자에게 메시지를 보내도록 만들어지며 위임 패턴은 일대일 통신을위한 것입니다. 따라서 싱글 톤을 사용하지 않고 위임 패턴을 사용하거나 싱글 톤을 사용하고 NSNotificationCenter을 사용하여 관찰자에게 변경 사항을 알리는 두 가지 옵션이 있습니다.

+1

위임자의 요구가 단순한 경우 위임 대신 블록을 사용하는 것이 좋습니다 (예 : 백그라운드 스레드에서 실행되는 FetchData 메서드). – Marc

+0

그리고 프로토콜 작성 및 위임에 대해 쓴 것은 - 그것이 옳은 방향인가 잘못된 방향인가? 내가 제안 할 수 있을까? – Neznajka

+0

@ 네즈 나카 : 정확히 무슨 뜻인지 모르겠습니다. 위임은 매우 일반적으로 사용되는 프로토콜 구현 중 하나 일뿐입니다. 이 경우에는 하나를 만드는 것이 의미가 없지만 다른 경우에는 많이 만듭니다. –