問題描述
我有一個接收 Class
對象的 NSArray
的方法,我需要檢查它們是否都是使用代碼生成的 Class
類型如下:
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"];
問題是Class
不是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
變量是否是 Class
類型,我想它會直接在 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?
如果答案還提供了一種方法來檢查數(shù)組中的項目是否為 NSObject
,這將是一個加分項,如示例代碼中的項目,NSPredicate
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
推薦答案
要確定對象"是類還是實例,您需要檢查它是否是 元類在一個兩階段的過程中.首先調(diào)用 object_getClass
然后使用 class_isMetaClass
.您將需要 #import <objc/runtime.h>
.
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));
Class
和 *id
都有相同的結(jié)構(gòu)布局(Class isa
),因此可以偽裝成對象,并且都可以接收消息很難確定哪個是哪個.這似乎是我能夠獲得一致結(jié)果的唯一方法.
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
類:NSPredicate
實例:不是類對象
Class: NSObject
Class: NSValue
Class: NSNumber
Class: NSPredicate
Instance: not a class object
這篇關(guān)于檢查對象是否為類類型的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!