检查对象是类类型

检查对象是类类型

本文介绍了检查对象是类类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有收到的NSArray 的对象,我需要检查,如果他们都是一个方法与code波纹管式生成的:

I have a method that receives a NSArray of Class objects and I need to check if they all are Class type generated with the code bellow:

NSMutableArray *arr = [[NSMutableArray alloc] init];

[arr addObject:[NSObject class]];
[arr addObject:[NSValue class]];
[arr addObject:[NSNumber class]];
[arr addObject:[NSPredicate class]];
[arr addObject:@"not a class object"];

问题是,不是一个Objective-C类,它是一个STRUC,所以我不能只用

The problem is that Class is not an objective-c class, it is a struc, so I can not use just

    for (int i; i<[arr count]; i++) {
        Class obj = [arr objectAtIndex:i];

        if([obj isKindOfClass: [Class class]]) {
            //do sth
        }
    }

所以,我需要我检查 OBJ 变量是一个键入,我想这将是在 C 直接,但我怎么能做到这一点?

So, I need to I check if the obj variable is a Class type, I suppose it will be in C directly, but how can I do that?

这将是一个加号,如果答案还提供了一种方法来检查,如果数组中的项目是 NSObject的,如例如code项中, NS predicate 也将是真正 NSObject的检查

It will be a plus if the answer also provide a way to check if the item in the array is a NSObject, as the items in the example code, the NSPredicate would also be true for the NSObject check

推荐答案

要确定一个对象是需要检查一个类或实例,如果它是一个的在两阶段过程。首先调用<$c$c>object_getClass然后检查它是否是使用元类<$c$c>class_isMetaClass.您需要将#进口&LT; objc / runtime.h方式&gt;

To determine if an "object" is a class or an instance you need to check if it is a meta class in a two stage process. First call object_getClass then check if it is a meta class using class_isMetaClass. You will need to #import <objc/runtime.h>.

NSObject *object = [[NSObject alloc] init];
Class class = [NSObject class];

BOOL yup = class_isMetaClass(object_getClass(class));
BOOL nope = class_isMetaClass(object_getClass(object));

两者 * ID 具有相同的结构布局(类ISA ),因此可以伪装成对象和既可以接收消息使得它很难确定哪个是哪个。这似乎是我能得到一致的结果的唯一途径。

Both Class and *id have the same struct layout (Class isa), therefore can pose as objects and can both receive messages making it hard to determine which is which. This seems to be the only way I was able to get consistent results.

编辑:

下面是您与原支票例如:

Here is your original example with the check:

NSMutableArray *arr = [[NSMutableArray alloc] init];

[arr addObject:[NSObject class]];
[arr addObject:[NSValue class]];
[arr addObject:[NSNumber class]];
[arr addObject:[NSPredicate class]];
[arr addObject:@"not a class object"];

for (int i; i<[arr count]; i++) {
    id obj = [arr objectAtIndex:i];

    if(class_isMetaClass(object_getClass(obj)))
    {
        //do sth
        NSLog(@"Class: %@", obj);
    }
    else
    {
        NSLog(@"Instance: %@", obj);
    }
}

[arr release];

和输出:

类:NSObject的

  类别:NSValue

  类别:
的NSNumber
  类别:NS predicate

  实例:不是一个类的对象

这篇关于检查对象是类类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 04:18