Iphone 如何使用ivar\u getTypeEncoding&;动态确定和比较对象ivars的类型@编码

Iphone 如何使用ivar\u getTypeEncoding&;动态确定和比较对象ivars的类型@编码,iphone,objective-c,ios,ipad,objective-c-runtime,Iphone,Objective C,Ios,Ipad,Objective C Runtime,下面是我要执行的比较操作: // foobar is the name of an ivar on some class // i.e. NSDate *foobar; const char *ivarType = [self getTypeForInstanceVariableWithName:@"foobar"]; const char *objType = @encode(NSDate); if (strcmp(ivarType, objType) == 0) { //set

下面是我要执行的比较操作:

// foobar is the name of an ivar on some class
// i.e. NSDate *foobar;
const char *ivarType = [self getTypeForInstanceVariableWithName:@"foobar"];
const char *objType  = @encode(NSDate);

if (strcmp(ivarType, objType) == 0) {
    //set value 
} 

NSLog(@"comparing %s with %s", ivarType, objType);
- (const char*)getTypeForInstanceVariableWithName:(NSString *)name {
     return ivar_getTypeEncoding(class_getInstanceVariable([self class], [name cStringUsingEncoding:NSUTF8StringEncoding]));
}
comparing @"NSDate" with {NSDate=#}
助手方法:

// foobar is the name of an ivar on some class
// i.e. NSDate *foobar;
const char *ivarType = [self getTypeForInstanceVariableWithName:@"foobar"];
const char *objType  = @encode(NSDate);

if (strcmp(ivarType, objType) == 0) {
    //set value 
} 

NSLog(@"comparing %s with %s", ivarType, objType);
- (const char*)getTypeForInstanceVariableWithName:(NSString *)name {
     return ivar_getTypeEncoding(class_getInstanceVariable([self class], [name cStringUsingEncoding:NSUTF8StringEncoding]));
}
comparing @"NSDate" with {NSDate=#}
NSLog结果:

// foobar is the name of an ivar on some class
// i.e. NSDate *foobar;
const char *ivarType = [self getTypeForInstanceVariableWithName:@"foobar"];
const char *objType  = @encode(NSDate);

if (strcmp(ivarType, objType) == 0) {
    //set value 
} 

NSLog(@"comparing %s with %s", ivarType, objType);
- (const char*)getTypeForInstanceVariableWithName:(NSString *)name {
     return ivar_getTypeEncoding(class_getInstanceVariable([self class], [name cStringUsingEncoding:NSUTF8StringEncoding]));
}
comparing @"NSDate" with {NSDate=#}
为什么@encode返回与ivar_getTypeEncoding()不同的类型语法?有没有更好的方法来完成这种类型的确定?我一定是错过了什么。。。
谢谢

使用ivar_getTypeEncoding()时,必须注意第一个字符。让我们看一个例子:

如果您有一个基本类型,那么第一个字符就是您得到的所有字符,对于int它将是'i',对于char'c',对于unsigned long'Q',等等

对于对象和类,您可能会得到更多,就像在您的示例中一样,但第一个字符是您想要的,比如@For objects、#For class、:For selector

你可以阅读这些类型。你也可以在比较时使用常量,比如_C_ID,_C_CLASS等等。在这里有一个战利品

C数组看起来比较棘手,但我相信你可以解决这个问题

代码中的一个问题是,您得到的是NSDate类的类型编码,而不是NSDate对象的类型编码。因此,与其与@encode(NSDate)进行比较,不如与@encode(NSDate*)进行比较

要查看这类代码的实际运行情况,请查看示例