私はコアデータが初めてです。オブジェクト指向の方法で実装しようとしています。サンプル プロジェクトとして、コア データを介して sqlite データベースからのデータを表示するビュー コントローラーを作成し、データは別のビュー コントローラーによって入力されます。ただし、モデル クラス「ContextHandler」を介してデータのフェッチと挿入を処理したかったので、別のモデル クラス「Device」を作成しました。これは のサブクラスですNSManagedObject
。
ただし、データを取得するときは、以前に入力したデータを再入力しています。
私のエンティティ モデル クラスの名前は「Device」です。
Device.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];
それをすると、アプリがクラッシュします。誰でもここで私を助けてくれませんか。