2013-10-31 125 views
1

我使用的核心数据,并一直在使用这样的代码名称:获得属性不是值

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

我想提出这样的代码进入一个循环,我所有的coredata名称是相同的作为属性名称。我怎么能说forKey:self.comments.name并得到与上述相同的结果或类似的东西?

编辑:

如果这是不可能的,有另一种方式设置一吨价值为从性质coredata?我有50多个属性和属性需要设置,并且希望避免使用现在正在执行的操作。

+0

我可能是错的,但我认为你不能在运行时获得 – KIDdAe

+0

什么是self,什么是self.form? –

+0

'@property(strong,nonatomic)IBOutlet UITextView * comments; @property(strong,retain)NSManagedObject * form;' – BluGeni

回答

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); 
} 
+0

我会给这个镜头,这似乎是我在找的东西。使用此代码的 – BluGeni

+0

,我可以在不使用idx的情况下获取属性名称吗? – BluGeni

+0

由于U获得了在类中声明的属性的列表,因此您必须进行索引才能访问它们。 – imihaly

0

reading the docs on CoreData确实不能替代reading the docs on 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); 
} 

在这个例子中,我现在有我的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文件...

0

一种方法是申报自己的属性的数组。

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]; 
} 

或者你可以使用this如果你希望你的核心数据模型的所有属性。