目标C:如何检查变量是NSArray还是NSM​​utableArray [英] Objective C: how to check if variable is NSArray or NSMutableArray

查看:86
本文介绍了目标C:如何检查变量是NSArray还是NSM​​utableArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查变量是NSArray还是NSM​​utableArray?

How can i check if a variable is an NSArray or an NSMutableArray?

推荐答案

**请注意,自编写此答案以来,NS {,Mutable} Array的实现已更改.结果,isKindOfClass:现在可以工作了.我不知道在什么平台上何时何地.

*Note that the implementation of NS{,Mutable}Array has changed since this answer was written. As a result, isKindOfClass: now works. On what platforms where and when, I don't know.

除非被证明是安全的,否则我将强烈建议不要编写试图检测集合是可变的还是不可变的代码.即使是安全的,这种设计模式也几乎总是表明存在严重的设计缺陷.

Until it is documented as safe to do so, I would strongly recommend NOT writing code that tries to detect whether a collection is mutable or immutable. Even if it were safe, such a design pattern is almost always indicative of a serious design flaw.

(对于具有访问权限的用户)提起rdar://10355515要求澄清.

(For those with access) Filed rdar://10355515 asking for clarification.

考虑:

int main (int argc, const char * argv[]) {
    NSArray *array = [NSArray arrayWithObjects: [NSObject new], nil];
    NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects: [NSObject new], nil];

    NSLog(@"array's class: %@", NSStringFromClass([array class]));
    NSLog(@"mutableArray's class: %@", NSStringFromClass([mutableArray class]));

    NSLog(@"array responds to addObject: %@", 
          [array respondsToSelector: @selector(addObject:)] ? @"YES" : @"NO");

    return 0;
}

(我使用非空数组,因为空的NSArray很常见,以至于Cocoa提供了一个共享实例作为优化.)

(I'm using non-empty arrays because an empty NSArray is common enough that Cocoa offers a single shared instance as an optimization.)

array's class: NSCFArray
mutableArray's class: NSCFArray
array responds to addObject: YES

-isKindOfClass:和检查addObject:的实现均无效.

I.e. neither -isKindOfClass: nor checking for implementation of addObject: will work.

简而言之,您无法分辨出NSArray和NSMutableArray之间的区别.这是设计使然,也是非常预期的行为.对于NSStringNSDictionaryNSSet(它们都有一个 mutable 子类)也是如此.

In short, you can't tell the difference between an NSArray and an NSMutableArray. This is by design and very much the intended behavior. It also holds true for NSString, NSDictionary and NSSet (all of which have a mutable subclass).

这可能令人惊讶.但是,现实情况是,需要检查可变性的设计模式会导致使用混乱,并产生大量开销.

That may come as a surprise. The reality, though, is that design patterns that require checking for mutability are confusing to use and incur significant overhead.

例如,如果可变性测试是一种常见模式,那么Cocoa中所有返回NSArray实例的方法都必须实际上返回NSArray实例,而绝不返回对内部的引用.可能正在使用.

For example, if test-for-mutability were a common pattern than all of the methods in Cocoa that return NSArray instances would have to actually return NSArray instances and never return a reference to the internal NSMutableArray that might be being used.

这篇关于目标C:如何检查变量是NSArray还是NSM​​utableArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆