1

私はコアデータを使用しており、次のようなコードを使用しています:

[self.form setValue:self.comments.text forKey:@"comments"];

このようなコードをループに入れたいのですが、コアデータ名はすべてプロパティ名と同じです。forKey:self.comments.name上記またはそのようなものと同じ結果をどのように言って取得できますか?

編集:

これが不可能な場合、プロパティからコアデータに大量の値を設定する別の方法はありますか? 設定する必要がある 50 以上の属性とプロパティがあり、現在行っていることの使用を避けたいと考えています。

4

3 に答える 3

3

本当に必要な場合は、objc/runtime.h の次の関数を使用できます。

objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount) // To get properties declared by a class.
const char *property_getName(objc_property_t property) // To get the name of one property

このようなもの:

unsigned int propCount = 0;
objc_property_t *properties = class_copyPropertyList([self class], &propCount);

for(int idx = 0; idx < propCount; idx++) {
    objc_property_t prop = *(properties + idx);
    NSString *key = @(property_getName(prop));
    NSLog(@"%@", key);
}
于 2013-10-31T14:20:14.867 に答える
0

CoreData のドキュメントを読むことに代わるものは実際にはありません。使用するパターンと構文は、少し足を伸ばさなければまったく明らかではないからです。

つまり、通常はデータ ストアから NSManagedObject サブクラスのインスタンスをフェッチします。

NSManagedObjectContext* moc = [delegate managedObjectContext];
NSEntityDescription* description = [NSEntityDescription entityForName:@"Filter" inManagedObjectContext:moc];
NSSortDescriptor* descriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
NSFetchRequest* request = [[NSFetchRequest alloc] init];
[request setEntity:description];
[request setSortDescriptors:[NSArray arrayWithObject:descriptor]];
NSError *error;
_enabledFilters = [NSMutableArray arrayWithArray:[moc executeFetchRequest:request error:&error]];
if (error) {
    NSLog(@"%@",error.localizedDescription);
}

この例では、「Filter」と呼ばれる NSManagedObject のインスタンスの配列があります。

次に、参照する適切なインスタンスを選択し、単純なドット構文でそのすべての属性にアクセスできます。

Filter* thisFilter = (Filter*)[_displayFilters objectAtIndex:indexPath.row];
cell.label.text = thisFilter.name;
cell.label.backgroundColor = [UIColor clearColor];
NSString*targetName = thisFilter.imageName;
UIImage *image = [UIImage imageNamed:targetName];
cell.image.image = image;

これで、永続データ ストアから情報を取得し、それをアプリ内で使用しました。

逆に、データ ストア内のインスタンスへの書き込みは、NSManagedObject サブクラスのインスタンスの属性を直接設定saveし、コンテキストを呼び出して変更をストアにプッシュするという点で、わずかに異なります。

TL;DR - CoreData ドキュメントに 1 時間か 2 時間費やすのはあなた自身の責任です...

于 2013-10-31T14:15:44.933 に答える
0

1 つの方法は、属性の配列を自分で宣言することです。

NSArray *attributes = [NSArray arrayWithObjects:..., @"comments", .., nil]; // or a NSSet
for(NSString *attribute in attributes){
    NSString *text = [[self performSelector:NSSelectorFromString(attribute)] text]; // presuming that it's safe to call 'text' on all your properties
    [self.form setValue:text forKey:attribute];
}

または、コア データ モデルのすべての属性が必要な場合は、これを使用できます。

于 2013-10-31T17:28:11.510 に答える