How to get an Objective-C class for ivar?

I have a bunch of simple ones NSManagedObjectthat I create in unit test. They have only one nametype attribute NSString *. I always give NSManagedObjectthe same entityNameand Classname.

I want to not write the following code 30 times in order to configure unit test:

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

- (void) setUp {
  [super setUp];

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

Since fooivar is, I think I would have to write a macro to capture type foo( foo) and use to create mine foo:

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

However, this raises the following warning in clang:

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

I also thought that I could try to determine the type using objective-c runtime IVarfrom Ivar class_getInstanceVariable(Class cls, const char* name), but the only type information IVaravailable from the type encoding from ivar_getTypeEncodingis equal id, which is not enough.

- IVar ?

+5
3

ivar, , @property . , :

@property (copy) NSString *normalString;

( property_getAttributes()) :

T@"NSString",C,VnormalString

.

, , NSClassFromString() .

: , , , .

+6

An id - id. Objective-C (objc_object). ObjC. , , . , ( objc_object), . : C-, , ( ivars).

, , , , .

+5

Perhaps I misunderstand what you are trying to achieve. To get the iVar class, you cannot use the iVar class method?

as:

NSString *aString = @"random string";
NSLog(@"%@",NSStringFromClass([aString class]));
0
source

All Articles