我有一个 user 表和一个 Girls 表和一个 Girls_result 表。
基本上我只想要USER
实体中的一个用户,那个 USER 是设备所有者,我想在每次需要时调用同一个 USER。
USER可以有多个女孩,女孩可以有多个结果。
数据模型:
USER <------>>GIRLS<-------->>GIRLS_RESULTS
因此,我将 user_deviceid 属性添加到 USER Entity 并创建了一个单例类,这样我就可以为 user 设置一个唯一编号,并在需要时调用它。我想确保没有创建具有相同 UUID 的多个用户对象。
@implementation SingletonClass
@synthesize singletonManagedObjectContext=_singletonManagedObjectContext;
@synthesize userIS=_userIS;
+ (SingletonClass *)sharedInstance
{
static SingletonClass *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[SingletonClass alloc] init];
// Do any other initialisation stuff here
});
return sharedInstance;
}
- (id)init {
if (self = [super init]) {
// set a singleton managed object context
_singletonManagedObjectContext=self.singletonManagedObjectContext;
//set only one user based on unique device id, so all tables will belong to that user
NSManagedObjectContext *context = _singletonManagedObjectContext;
//how to make sure that _userIS is the same user all the time???
if (_userIS.user_deviceid == [self newUUID]) {
NSLog(@"user dvice id matches");
}
else{
_userIS.user_deviceid=[self newUUID];
}
}
return self;
}
- (NSString *)newUUID
{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return (NSString *)CFBridgingRelease(string);
}
那么如何确保在 USER 实体中只创建一个 USER 并且每次都可以使用该特定 USER 呢?
============编辑答案============ 基于接受的答案 下面我创建了一个工作正常的类
#import "CheckUser.h"
#import "USER.h"
#import "SingletonClass.h"
@implementation CheckUser
- (USER *)checkandreturnUser
{
SingletonClass *sharedInstance = [SingletonClass sharedInstance];
NSManagedObjectContext *context = sharedInstance.singletonManagedObjectContext;
// Fetch Form Object
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"USER"
inManagedObjectContext:context]];
USER *user;
NSError *error = nil;
NSArray *userArray = [context executeFetchRequest:fetchRequest error:&error];
NSLog(@"user array count %i",[userArray count]);
if (userArray == nil) {
NSAssert(0, @"There was an error fetching user object");
userArray = [NSArray array];
}
// If user doesn't exist create it
if ([userArray count] > 0) {
NSAssert([userArray count] == 1, @"Expected one user but there were more");
user = [userArray objectAtIndex:0];
} else {
//Create user object
user = [NSEntityDescription insertNewObjectForEntityForName:@"USER"
inManagedObjectContext:context];
user.user_deviceid=[self newUUID];
// maybe save here?
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}
return user;
}
- (NSString *)newUUID
{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return (NSString *)CFBridgingRelease(string);
}