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