变更记录

序号 录入时间 录入人 备注
1 2015-03-03 Alfred Jiang -
2 2015-12-22 Alfred Jiang -

方案名称

CoreData - 使用 FYHDBManager 管理 CoreData

关键字

CoreData \ 数据库 \ FYHDBManager

需求场景

  1. 部分轻型小应用的数据库需求

参考链接

(无)

详细内容

#####定义

FYHDBHeader.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//
// FYHDBHeader.h
// GrandJustice
//
// Created by Alfred Jiang on 3/3/15.
// Copyright (c) 2015 FYH. All rights reserved.
//

#ifndef GrandJustice_FYHDBHeader_h
#define GrandJustice_FYHDBHeader_h

#define NAME_OF_SQLITE @"GrandJustice.sqlite"
#define NAME_OF_MODELD @"GrandJustice"

//根据实际需要增加实体定义
#define ENTITY_RESULT_ITEM_NAME @"GJResultItem"
#define ENTITY_GJPLAYER_NAME @"GJPlayer"

#endif

FYHDBManager.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//
// FYHDBManager.h
// ALFNote
//
// Created by FYH on 7/22/14.
// Copyright (c) 2014 FYH. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import "FYHDBHeader.h"

typedef void (^FYHDBOperationCompletionBlock) (NSInteger type, NSError *error);

typedef NS_ENUM(NSInteger, ResultType) {
ResultType_Success = 1,
ResultType_Not_Exist = -1000,
ResultType_Save_Failed,
ResultType_Delete_Failed,
ResultType_Clear_Failed,
ResultType_Fetch_Failed,
};

typedef NS_ENUM(NSInteger, OperationType) {
OperationType_Save = 0,
OperationType_Delete,
};

@interface FYHDBManager : NSObject

- (id)init;
- (NSManagedObjectContext *)mainManagedObjectContext;
- (NSManagedObjectModel *)managedObjectModel;
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory;
- (void)saveManagedObject:(NSManagedObject *)object completion:(FYHDBOperationCompletionBlock)completionBlock;
- (void)deleteDBObject:(id)object completion:(FYHDBOperationCompletionBlock)completionBlock;
- (NSArray *)fetchDataArrayForEntity:(NSString *)entityName
byPredicates:(NSPredicate *)predicate
sortDescriptors:(NSArray *)sortDescriptiors
inManagedObjectContext:(NSManagedObjectContext *)context;

@end

FYHDBManager.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
//
// FYHDBManager.m
// ALFNote
//
// Created by FYH on 7/22/14.
// Copyright (c) 2014 FYH. All rights reserved.
//

#import "FYHDBManager.h"
#import <CoreData/CoreData.h>

@interface FYHDBManager()
{
NSManagedObjectContext * __mainManagedObjectContext;
NSManagedObjectModel * __managedObjectModel;
NSPersistentStoreCoordinator * __persistentStoreCoordinator;
}

@end

@implementation FYHDBManager

- (id)init
{
self = [super init];

__mainManagedObjectContext = [self mainManagedObjectContext];

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(mergeChanges:) name:NSManagedObjectContextDidSaveNotification object:nil];

return self;
}

#pragma mark - CoreData method

- (void)mergeChanges:(NSNotification *)notification {
NSManagedObjectContext *savedContext = [notification object];

// ignore change notifications for the main MOC
if (__mainManagedObjectContext == savedContext)
{
return;
}

dispatch_sync(dispatch_get_main_queue(), ^{
[__mainManagedObjectContext mergeChangesFromContextDidSaveNotification:notification];
});
//this tells the main thread moc to run on the main thread, and merge in the changes there
//[__mainManagedObjectContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) withObject:notification waitUntilDone:YES];
}

- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.mainManagedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}

#pragma mark - Core Data stack

-(void)saveManagedObject:(NSManagedObject *)object completion:(FYHDBOperationCompletionBlock)completionBlock
{
NSManagedObjectContext *moc = object.managedObjectContext;

if (moc == __mainManagedObjectContext) {
[moc performBlockAndWait:^{
NSError *error;
[moc save:&error];
completionBlock(OperationType_Save, error);
}];
}
else
{
NSError *error = [NSError errorWithDomain:@"db" code:0 userInfo:@{NSLocalizedDescriptionKey:@"db save context fault"}];
completionBlock(OperationType_Save, error);
}
}

-(void)deleteDBObject:(id)object completion:(FYHDBOperationCompletionBlock)completionBlock
{
NSManagedObjectContext *moc = ((NSManagedObject *)object).managedObjectContext;
__block NSError *error;

[moc performBlockAndWait:^{
[moc deleteObject:object];
[moc save:&error];
completionBlock(OperationType_Delete, error);
}];
}

#pragma mark -

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)mainManagedObjectContext
{
if (__mainManagedObjectContext) {
return __mainManagedObjectContext;
}

NSManagedObjectContext * __managedObjectContext = nil;

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
__managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return __managedObjectContext;
}

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil) {
return __managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:NAME_OF_MODELD withExtension:@"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
return __persistentStoreCoordinator;
}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:NAME_OF_SQLITE];
NSLog(@"AMDBManager storeUrl %@",storeURL);
NSError *error = nil;

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
{
/*
Replace this implementation with code to handle the error appropriately.

abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.

Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.


If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}

return __persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

#pragma mark -

#pragma mark - Internal Method
- (NSArray *)fetchDataArrayForEntity:(NSString *)entityName
byPredicates:(NSPredicate *)predicate
sortDescriptors:(NSArray *)sortDescriptiors
inManagedObjectContext:(NSManagedObjectContext *)context
{
__block NSArray *fetchedObjects = nil;

if (context == __mainManagedObjectContext)
{
[context performBlockAndWait:^{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:predicate];
[fetchRequest setSortDescriptors:sortDescriptiors];

NSError *error = nil;
fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil || error) {
fetchedObjects = nil;
}
}];
}
else
{
NSLog(@"error: fetching from unknown context");
}

return fetchedObjects;
}

@end

#####用法

DBManager.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//
// DBManager.h
// YLAlbum
//
// Created by FYH on 7/29/14.
// Copyright (c) 2014 FYH. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "FYHDBManager.h"
#import "GJResultItem.h"
#import "GJPlayer.h"

@interface DBManager : FYHDBManager

+ (DBManager *)sharedManager;

#pragma mark - GJResultItem

- (GJResultItem *)createWithAInfo:(NSString *)aAinfo
BInfo:(NSString *)aBinfo
FInfo:(NSString *)aFinfo
GInfo:(NSString *)aGinfo
Version:(NSString *)aVersion
Type:(NSString *)aType;

- (ResultType)deleteGJResultItemById:(NSString *)aId;
- (ResultType)updateGJResultItem:(GJResultItem *)aGJResultItem;
- (GJResultItem *)GJResultItemById:(NSString *)aId;
- (NSArray *)allGJResultItemsByVersion:(NSString *)aVersion andType:(NSString *)aType;
- (NSArray *)allGJResultItemsByType:(NSString *)aType;
- (NSArray *)allGJResultItems;
- (ResultType)clearallValidGJResultItems;
- (NSArray *)resultItemByItemA:(NSString *)aAinfo ItemB:(NSString *)aBinfo ItemF:(NSString *)aFinfo ItemG:(NSString *)aGinfo forVersion:(NSString *)aVersion;
- (BOOL)isExistItemA:(NSString *)aAinfo ItemB:(NSString *)aBinfo ItemF:(NSString *)aFinfo ItemG:(NSString *)aGinfo forVersion:(NSString *)aVersion;

#pragma mark - GJPlayer

- (GJPlayer *)createGJPlayerWithpRoleInfo:(NSString *)apRoleInfo pName:(NSString *)apName pPhone:(NSString *)apPhone pRole:(NSString *)apRole;
- (ResultType)deleteGJPlayerById:(NSString *)aId;
- (GJPlayer *)GJPlayerById:(NSString *)aId;
- (ResultType)updateGJPlayer:(GJPlayer *)aGJPlayer;
- (NSArray *)allGJPlayers;
- (ResultType)clearallValidGJPlayers;

#pragma mark - GJTestPlayer

- (GJPlayer *)createGJTestPlayerWithpRoleInfo:(NSString *)apRoleInfo pName:(NSString *)apName pPhone:(NSString *)apPhone pRole:(NSString *)apRole;
- (ResultType)deleteGJTestPlayerById:(NSString *)aId;
- (GJPlayer *)GJTestPlayerById:(NSString *)aId;
- (ResultType)updateGJTestPlayer:(GJPlayer *)aGJPlayer;
- (NSArray *)allGJTestPlayers;
- (ResultType)clearallValidGJTestPlayers;

@end

DBManager.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//
// DBManager.m
// YLAlbum
//
// Created by FYH on 7/29/14.
// Copyright (c) 2014 FYH. All rights reserved.
//

#import "DBManager.h"

@implementation DBManager

+ (NSString *)randmIdFor:(NSString *)aTitle {
NSString *strId = [aTitle stringByAppendingString:[[NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]] stringByReplacingOccurrencesOfString:@"." withString:@""]];
return [strId stringByAppendingString:[NSString stringWithFormat:@"%u",arc4random_uniform(10000)]];
}

+(DBManager *)sharedManager
{
static DBManager *sharedManager;

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedManager = [[DBManager alloc] init];
});

return sharedManager;
}

#pragma mark - GJResultItem

- (GJResultItem *)createWithAInfo:(NSString *)aAinfo
BInfo:(NSString *)aBinfo
FInfo:(NSString *)aFinfo
GInfo:(NSString *)aGinfo
Version:(NSString *)aVersion
Type:(NSString *)aType
{
NSArray *list = [self resultItemByItemA:aAinfo ItemB:aBinfo ItemF:aFinfo ItemG:aGinfo forVersion:aVersion];
if (list && [list count] != 0) {
return list.firstObject;
}

NSManagedObjectContext * __managedObjectContext = [self mainManagedObjectContext];

GJResultItem *aGJResultItem = (GJResultItem *)[NSEntityDescription insertNewObjectForEntityForName:ENTITY_RESULT_ITEM_NAME inManagedObjectContext:__managedObjectContext];

aGJResultItem.rId = [[self class] randmIdFor:@"ResultItem"];
aGJResultItem.rAInfo = aAinfo;
aGJResultItem.rBInfo = aBinfo;
aGJResultItem.rFInfo = aFinfo;
aGJResultItem.rGInfo = aGinfo;
aGJResultItem.rVersion = aVersion;
aGJResultItem.rType = aType;
aGJResultItem.rCount = @"0";
aGJResultItem.rTime = [[NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]] stringByReplacingOccurrencesOfString:@"." withString:@""];
aGJResultItem.rEditing = @"0";
aGJResultItem.rValid = @"1";

ResultType type = [self updateGJResultItem:aGJResultItem];

if (type != ResultType_Success) {

aGJResultItem = nil;

}

return aGJResultItem;
}

- (ResultType)deleteGJResultItemById:(NSString *)aId
{
GJResultItem *GJResultItem = [self GJResultItemById:aId];

if (!GJResultItem) {
return ResultType_Not_Exist;
}

ResultType type = ResultType_Success;

[self deleteDBObject:GJResultItem completion:^(NSInteger type, NSError *error) {
if (error) {
type = ResultType_Delete_Failed;
NSLog(@"%ld",(long)type);
NSLog(@"Error to Create New GJResultItem!");
}
}];

return type;
}

- (ResultType)updateGJResultItem:(GJResultItem *)aGJResultItem
{
ResultType type = ResultType_Success;

[self saveManagedObject:aGJResultItem completion:^(NSInteger type, NSError *error) {
if (error) {
type = ResultType_Delete_Failed;
NSLog(@"%ld",(long)type);
NSLog(@"Error to Delete New GJResultItem!");
}
}];

return type;
}

- (GJResultItem *)GJResultItemById:(NSString *)aId
{
NSPredicate * filter = [NSPredicate predicateWithFormat:@"rId = %@", aId];
NSArray *array = [self fetchDataArrayForEntity:ENTITY_RESULT_ITEM_NAME
byPredicates:filter
sortDescriptors:nil
inManagedObjectContext:[self mainManagedObjectContext]];
return array.firstObject;
}

- (NSArray *)allGJResultItemsByVersion:(NSString *)aVersion andType:(NSString *)aType
{
NSPredicate * filter = nil;

filter = [NSPredicate predicateWithFormat:@"rVersion = %@", aVersion];

NSSortDescriptor *sortDescriptor = nil;

if ([aType isEqualToString:@"1"])
{
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"rCount" ascending:NO];
}
else
{
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"rAInfo" ascending:YES];
}

NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor,nil];

NSArray *array = [self fetchDataArrayForEntity:ENTITY_RESULT_ITEM_NAME
byPredicates:filter
sortDescriptors:sortDescriptors
inManagedObjectContext:[self mainManagedObjectContext]];
return array;
}

- (NSArray *)allGJResultItemsByType:(NSString *)aType
{
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"rTime" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor,nil];

NSPredicate * filter = [NSPredicate predicateWithFormat:@"rType = %@",aType];
NSArray *array = [self fetchDataArrayForEntity:ENTITY_RESULT_ITEM_NAME
byPredicates:filter
sortDescriptors:sortDescriptors
inManagedObjectContext:[self mainManagedObjectContext]];
return array;
}

- (NSArray *)allGJResultItems
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];

NSEntityDescription *myEntityQuery = [NSEntityDescription
entityForName:ENTITY_RESULT_ITEM_NAME
inManagedObjectContext:[self mainManagedObjectContext]];

[request setEntity:myEntityQuery];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"rTime" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor,nil];
[request setSortDescriptors:sortDescriptors];

NSError *error =nil;
NSArray *DeviceArr = [[self mainManagedObjectContext] executeFetchRequest:request error:&error];
return DeviceArr;
}

- (ResultType)clearallValidGJResultItems
{
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];

[fetch setEntity:[NSEntityDescription entityForName:ENTITY_RESULT_ITEM_NAME inManagedObjectContext:[self mainManagedObjectContext]]];

ResultType type = ResultType_Success;

NSError *error =nil;
NSArray *dbList = [[self mainManagedObjectContext] executeFetchRequest:fetch error:&error];
if (error) {
type = ResultType_Fetch_Failed;
NSLog(@"Error to Create New GJResultItem!");
}

for (id object in dbList) {
[self deleteDBObject:object completion:^(NSInteger type, NSError *error) {
if (error) {
type = ResultType_Clear_Failed;
NSLog(@"%ld",(long)type);
NSLog(@"Error to Create New GJResultItem!");
}
}];
}

return type;
}

- (NSArray *)resultItemByItemA:(NSString *)aAinfo ItemB:(NSString *)aBinfo ItemF:(NSString *)aFinfo ItemG:(NSString *)aGinfo forVersion:(NSString *)aVersion
{
NSPredicate *filter = [NSPredicate predicateWithFormat:@"rVersion = %@ && rAInfo = %@ && rBInfo = %@ && rFInfo = %@ && rGInfo = %@", aVersion,aAinfo,aBinfo,aFinfo,aGinfo];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"rTime" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor,nil];

NSArray *array = [self fetchDataArrayForEntity:ENTITY_RESULT_ITEM_NAME
byPredicates:filter
sortDescriptors:sortDescriptors
inManagedObjectContext:[self mainManagedObjectContext]];

return array;
}

- (BOOL)isExistItemA:(NSString *)aAinfo ItemB:(NSString *)aBinfo ItemF:(NSString *)aFinfo ItemG:(NSString *)aGinfo forVersion:(NSString *)aVersion
{
NSArray *array = [self resultItemByItemA:aAinfo ItemB:aBinfo ItemF:aFinfo ItemG:aGinfo forVersion:aVersion];
return (array && array.count > 0);
}

#pragma mark - GJPlayer

- (GJPlayer *)createGJPlayerWithpRoleInfo:(NSString *)apRoleInfo pName:(NSString *)apName pPhone:(NSString *)apPhone pRole:(NSString *)apRole
{
NSManagedObjectContext * __managedObjectContext = [self mainManagedObjectContext];

GJPlayer *aGJPlayer = (GJPlayer *)[NSEntityDescription insertNewObjectForEntityForName:ENTITY_GJPLAYER_NAME
inManagedObjectContext:__managedObjectContext];

aGJPlayer.pId = [[self class] randmIdFor:@"Player"];
aGJPlayer.pRoleInfo = apRoleInfo;
aGJPlayer.pName = apName;
aGJPlayer.pPhone = apPhone;
aGJPlayer.pRole = apRole;
aGJPlayer.pDirection = @"0";
aGJPlayer.pType = @"Normal";

ResultType type = [self updateGJPlayer:aGJPlayer];

if (type != ResultType_Success) {

aGJPlayer = nil;
}

return aGJPlayer;
}

- (ResultType)deleteGJPlayerById:(NSString *)aId
{
GJPlayer *aPlayer = [self GJPlayerById:aId];

if (!aPlayer) {
return ResultType_Not_Exist;
}

ResultType type = ResultType_Success;

[self deleteDBObject:aPlayer completion:^(NSInteger type, NSError *error) {
if (error) {
type = ResultType_Delete_Failed;
NSLog(@"%ld",(long)type);
NSLog(@"Error to Create New aPlayer!");
}
}];

return type;
}

- (GJPlayer *)GJPlayerById:(NSString *)aId
{
NSPredicate * filter = [NSPredicate predicateWithFormat:@"pId = %@", aId];
NSArray *array = [self fetchDataArrayForEntity:ENTITY_GJPLAYER_NAME
byPredicates:filter
sortDescriptors:nil
inManagedObjectContext:[self mainManagedObjectContext]];
return array.firstObject;
}

- (ResultType)updateGJPlayer:(GJPlayer *)aGJPlayer
{
ResultType type = ResultType_Success;

[self saveManagedObject:aGJPlayer completion:^(NSInteger type, NSError *error) {
if (error) {
type = ResultType_Save_Failed;
NSLog(@"Error to Delete New GJPlayer!");
}
}];

return type;
}

- (NSArray *)allGJPlayers
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];

NSEntityDescription *myEntityQuery = [NSEntityDescription
entityForName:ENTITY_GJPLAYER_NAME
inManagedObjectContext:[self mainManagedObjectContext]];

[request setEntity:myEntityQuery];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"pId" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor,nil];
[request setSortDescriptors:sortDescriptors];

NSPredicate * filter = [NSPredicate predicateWithFormat:@"pType = %@", @"Normal"];
[request setPredicate:filter ];

NSError *error =nil;
NSArray *GJPlayerArr = [[self mainManagedObjectContext] executeFetchRequest:request error:&error];
return GJPlayerArr;
}

- (ResultType)clearallValidGJPlayers
{
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];

[fetch setEntity:[NSEntityDescription entityForName:ENTITY_GJPLAYER_NAME inManagedObjectContext:[self mainManagedObjectContext]]];

NSPredicate * filter = [NSPredicate predicateWithFormat:@"pType = %@", @"Normal"];
[fetch setPredicate:filter ];

ResultType type = ResultType_Success;

NSError *error =nil;
NSArray *dbList = [[self mainManagedObjectContext] executeFetchRequest:fetch error:&error];
if (error) {
type = ResultType_Fetch_Failed;
NSLog(@"Error to Create New GJPlayer!");
}

for (id object in dbList) {
[self deleteDBObject:object completion:^(NSInteger type, NSError *error) {
if (error) {
type = ResultType_Clear_Failed;
NSLog(@"Error to Create New GJPlayer!");
}
}];
}

return type;
}

#pragma mark - GJTestPlayer

- (GJPlayer *)createGJTestPlayerWithpRoleInfo:(NSString *)apRoleInfo pName:(NSString *)apName pPhone:(NSString *)apPhone pRole:(NSString *)apRole
{
NSManagedObjectContext * __managedObjectContext = [self mainManagedObjectContext];

GJPlayer *aGJPlayer = (GJPlayer *)[NSEntityDescription insertNewObjectForEntityForName:ENTITY_GJPLAYER_NAME inManagedObjectContext:__managedObjectContext];

aGJPlayer.pId = [[self class] randmIdFor:@"Player"];
aGJPlayer.pRoleInfo = apRoleInfo;
aGJPlayer.pName = apName;
aGJPlayer.pPhone = apPhone;
aGJPlayer.pRole = apRole;
aGJPlayer.pDirection = @"0";
aGJPlayer.pType = @"Test";

ResultType type = [self updateGJPlayer:aGJPlayer];

if (type != ResultType_Success) {

aGJPlayer = nil;
}

return aGJPlayer;
}

- (ResultType)deleteGJTestPlayerById:(NSString *)aId
{
return [self deleteGJPlayerById:aId];
}

- (GJPlayer *)GJTestPlayerById:(NSString *)aId
{
return [self GJPlayerById:aId];
}

- (ResultType)updateGJTestPlayer:(GJPlayer *)aGJPlayer
{
return [self updateGJPlayer:aGJPlayer];
}

- (NSArray *)allGJTestPlayers
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];

NSEntityDescription *myEntityQuery = [NSEntityDescription
entityForName:ENTITY_GJPLAYER_NAME inManagedObjectContext:[self mainManagedObjectContext]];

[request setEntity:myEntityQuery];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"pId" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor,nil];
[request setSortDescriptors:sortDescriptors];

NSPredicate * filter = [NSPredicate predicateWithFormat:@"pType = %@", @"Test"];
[request setPredicate:filter ];

NSError *error =nil;
NSArray *GJPlayerArr = [[self mainManagedObjectContext] executeFetchRequest:request error:&error];
return GJPlayerArr;
}

- (ResultType)clearallValidGJTestPlayers
{
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];

[fetch setEntity:[NSEntityDescription entityForName:ENTITY_GJPLAYER_NAME inManagedObjectContext:[self mainManagedObjectContext]]];

NSPredicate * filter = [NSPredicate predicateWithFormat:@"pType = %@", @"Test"];
[fetch setPredicate:filter ];

ResultType type = ResultType_Success;

NSError *error =nil;
NSArray *dbList = [[self mainManagedObjectContext] executeFetchRequest:fetch error:&error];
if (error) {
type = ResultType_Fetch_Failed;
NSLog(@"Error to Create New GJPlayer!");
}

for (id object in dbList) {
[self deleteDBObject:object completion:^(NSInteger type, NSError *error) {
if (error) {
type = ResultType_Clear_Failed;
NSLog(@"Error to Create New GJPlayer!");
}
}];
}

return type;
}

@end

效果图

(无)

备注

类似推荐