本文介绍了如何获得ivar的Objective-C类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在单元测试中创建了一堆简单的NSManagedObject.它们仅具有类型为NSString *的单个name属性.我总是给我NSManagedObject相同的entityNameClass名称.

I have a bunch of simple NSManagedObjects I create in a unit test. They just have a single name attribute of type NSString *. I always give my NSManagedObject the same entityName and Class name.

我要避免必须编写30次以下代码来设置单元测试:

I want to avoid having to write the following code 30 times to set up a unit test:

@interface FooTest : GHTestCase {
Foo *foo;
}
@end
@implementation FooTest

- (void) setUp {
  [super setUp];

  foo = [NSEntityDescription insertNewObjectForEntityForName:@"Foo"
                                      inManagedObjectContext:managedObjectContext];
  foo.name = @"foo";
}
@end

由于foo是一个ivar,我想我应该能够编写一个宏来捕获foo(Foo)类型,并用于创建我的Foo:

Since foo is an ivar, I would think I should be able to write a macro to grab the type of foo (Foo), and use to create my Foo:

#define InsertManagedObjectByVariable(variable) \
do { \
variable = [NSEntityDescription insertNewObjectForEntityName:NSStringFromClass([typeof(variable) class])]; \
variable.name = (NSString *) CFSTR(#variable);
} while(0)

但是,这会导致以下警告:

However, this causes the following warning in clang:

variable = [NSEntityDescription insertNewObjectForEntityName:NSStringFromClass([typeof(variable) class])];
                                                                               ^
                                                             Expected expression

我还认为我可以尝试使用Ivar class_getInstanceVariable(Class cls, const char* name)中的Objective-c运行时IVar确定类型,但是ivar_getTypeEncoding的类型编码中唯一可用的IVar类型信息是id,即还不够.

I also thought I could try to determine the type using the objective-c runtime IVar from Ivar class_getInstanceVariable(Class cls, const char* name), but the only IVar type information available from the type encoding from ivar_getTypeEncoding is id, which isn't enough.

有人能想到一种在编译时或运行时获取IVar的类型信息的方法吗?

Can someone think of a way to obtain the type information of an IVar either at compile time or runtime?

推荐答案

我没有尝试从ivar获取类信息,但是我知道@property声明确实对有关类的信息进行了编码.例如,此属性声明:

I haven't tried obtaining class information from an ivar, but I know that @property declarations do encode information about the class. For instance, this property declaration:

@property (copy) NSString *normalString;

导致该属性字符串(使用 property_getAttributes())在运行时:

results in this attribute string (retrieved using property_getAttributes()) at runtime:

T@"NSString",C,VnormalString

我写了一些开源解析代码获取此信息.

一旦有了类名,就可以使用 NSClassFromString(),然后从那里通知结果.

Once you have the class name, you can convert it into an actual Class object using NSClassFromString(), and message the result from there.

免责声明:生产应用程序可能不应该依赖此文件,因为它没有记录.

Disclaimer: This probably shouldn't be depended upon for production applications, as it is undocumented.

这篇关于如何获得ivar的Objective-C类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 22:13