3

我阅读了有关单例和委托的足够信息。所以,我想我明白什么是单例。关于代表团,我仍然感到困惑。我理解委托的概念,但我需要创建我的协议来理解委托。

好的,我创建了单例来处理来自 CoreData 的实体。也许我错了,它不是单身,请告诉我。我的单身人士是 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

获取数据.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]

但我认为我可以用于我的目标代表团。或者,与单例相比,这可能是最好的选择。所以我想为委托重新制作单例。我需要这个问题的帮助。我应该做什么?

如果我理解正确,我需要使用 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

获取数据.m

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

@implementation FetchData
@synthesize //all properties and delegate

//implementation of methods
@end

某类

#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
4

1 回答 1

9

单例的想法是您的整个应用程序都可以访问这一类。多个视图控制器可能需要来自您的数据库的数据。在您的情况下,我会更改您的fetchData方法(并且可能会更改其名称,因为它现在并不真正遵循约定):

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

委托用于一对一通信,这意味着一个对象有一个委托并将任何消息发送给该特定委托。

这意味着单例和委托不能很好地结合在一起。单例用于向多个接收者发送消息,而委托模式用于一对一通信。所以你有两个选择:你可以不使用单例并使用委托模式,或者你可以使用单例,并使用NSNotificationCenter通知观察者更改。

于 2013-02-06T17:32:29.220 回答