寻找更好的方法来测试对象的类类型
在将 Scripting Bridge 与 Excel 结合使用时,当我获取单个单元格的值时,我不知道将从该单元格获取什么类。到目前为止,单个单元格的范围返回 NSString
或 NSNumber
(多个单元格的范围始终返回 NSArray
并且我需要强制值从那里)。在我的工作中,我通常只想要单元格的 string 值,因此为了将单个单元格范围的值强制转换为我需要的值,我这样做......
NSString *cellValue = [targetRange.value get];
if ([cellValue isKindOfClass:[NSString class]]) {
cellValue = [targetRange.value get];
} else if ([cellValue isKindOfClass:[NSNumber class]]) {
cellValue = [[targetRange.value get] stringValue];
}
我的问题在于第一个行(我们暂时忽略第三行,因为我仍在进行一些重构)。是否有更好的类来捕获单元格的值来测试类?最后三行工作正常,但我觉得这样做不太舒服;这看起来不直观,但使用 NSObject 感觉也很奇怪。
In using Scripting Bridge with Excel, when I get the value of a single cell, I don't know what class I'm going to get from the cell. A range of a single cell so far returns an NSString
or NSNumber
(a range of multiple cells always returns an NSArray
and I need to coerce the values from there). In my work, I usually only want the string value of the cell, so to coerce the value of a single-cell range into what I need, I do this...
NSString *cellValue = [targetRange.value get];
if ([cellValue isKindOfClass:[NSString class]]) {
cellValue = [targetRange.value get];
} else if ([cellValue isKindOfClass:[NSNumber class]]) {
cellValue = [[targetRange.value get] stringValue];
}
My problem lies with the first line (we'll ignore the third line for the time being as I'm still doing a bit of refactoring). Would there be a better class to capture the value of the cell to test for class against? Those last three lines work fine, but I don't feel entirely comfortable doing that; it seems unintuitive but going with NSObject
feels just as weird.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,您可以使用
id
:例如:
请注意,在您的情况下,您可能可以使用如下内容:
In such cases you can use
id
:E.g.:
Note that in your case you could probably just use something like this:
您是否询问在运行时检查对象的类并根据类的不同采取不同的行为是否“可以”或“正常”?如果是这样,那就是一个强调的是 - 这就是 Objective-C 如此强大的部分原因。
如果您问是否有更好的方法来确定对象的类,那么没有,没有。我的意思是你可以直接比较类( == ),但这并不总是明智的,考虑到类簇、子类等。
Are you asking if it's "okay" or "normal" to inspect an object's class at runtime and act differently depending on the class? If so, that's an emphatic yes - that's part of what makes Objective-C so powerful.
If you're asking if there's a better way of determining an object's class, then no, not really. I mean you can directly compare classes ( == ) but that's not always wise, given class clusters, subclasses, etc.