我是核心数据的新手。我正在尝试以面向对象的方式实现它。作为一个示例项目,我创建了一个视图控制器,它通过核心数据显示来自 sqlite 数据库的数据,并且数据由另一个视图控制器输入。但是,我想通过模型类“ContextHandler”处理数据获取和插入,并创建了另一个模型类“Device”,它是NSManagedObject
.
但是,在获取数据时,我正在重新输入以前输入的数据。
我的实体模型类被命名为“设备”。
设备.h -
#import <CoreData/CoreData.h>
@interface Device : NSManagedObject
@property(nonatomic, strong) NSString *name;
@property(nonatomic, strong) NSString *company;
@property(nonatomic, strong) NSString *version;
@end
和 Device.m -
#import "Device.h"
@implementation Device
@dynamic name;
@dynamic company;
@dynamic version;
@end
通过以下类,我正在插入和获取设备对象。
插入方法是
-(void)addDeviceWithName:(NSString*)name andCompany:(NSString*)company andVersion:(NSString*)version{
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Device" inManagedObjectContext:self.context];
Device *newDevice = [[Device alloc] initWithEntity:entity insertIntoManagedObjectContext:self.context];
newDevice.name = name;
newDevice.company = company;
newDevice.version = version;
NSError *error = nil;
if(![self.context save:&error]){
NSLog(@"Could not add due to %@ %@", error, [error localizedDescription]);
}
}
获取方法是-
-(NSMutableArray*)getDeviceListFromDatabase{
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Device"];
NSMutableArray *devices = [[self.context executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSMutableArray *deviceList =[[NSMutableArray alloc]initWithCapacity:[devices count]];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Device" inManagedObjectContext:self.context];
for(NSManagedObject *currentDevice in devices){
//here I am inserting the data again
Device *deviceObject = [[Device alloc] initWithEntity:entity insertIntoManagedObjectContext:self.context];
deviceObject.name = [currentDevice valueForKey:@"name"];
deviceObject.company = [currentDevice valueForKey:@"company"];
deviceObject.version = [currentDevice valueForKey:@"version"];
[deviceList addObject:deviceObject];
}
return deviceList;
}
问题是当我初始化设备对象时,我最终再次将对象添加到数据库中。
如何解决这个问题。如何在不再次插入数据的情况下初始化 Device 类。
我做不到——
Device *deviceObject = [[Device alloc] init];
如果我这样做,应用程序就会崩溃。任何人都可以在这里帮助我。