gpt4 book ai didi

objective-c - 如何测试对象在 Objective-C 中属于哪个类?

转载 作者:IT老高 更新时间:2023-10-28 12:15:01 25 4
gpt4 key购买 nike

如何在 Objective-C 中测试一个对象是否是特定类的实例?假设我想看看对象a是b类还是c类的实例,我该怎么做呢?

最佳答案

测试对象是否是a类的实例:

[yourObject isKindOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of
// given class or an instance of any class that inherits from that class.

[yourObject isMemberOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of a
// given class.

要获取对象的类名,您可以使用 NSStringFromClass 函数:

NSString *className = NSStringFromClass([yourObject class]);

或来自 Objective-c 运行时 api 的 c 函数:

#import <objc/runtime.h>

/* ... */

const char* className = class_getName([yourObject class]);
NSLog(@"yourObject is a: %s", className);

编辑:在 Swift 中

if touch.view is UIPickerView {
// touch.view is of type UIPickerView
}

关于objective-c - 如何测试对象在 Objective-C 中属于哪个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2055940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com