为什么有时可以将 NSArray 转换为 NSMutableArray,有时不能? [英] Why can you sometimes cast a NSArray to NSMutableArray, and sometimes you can't?

查看:56
本文介绍了为什么有时可以将 NSArray 转换为 NSMutableArray,有时不能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

特别是:

self.words = (NSMutableArray*)[self.text componentsSeparatedByString:@" "];

只要有分隔符就可以正常工作.不过,我看到该方法返回包裹在 NSArray 中的原始字符串(如果没有).这个单一元素的 NSArray 顽固地拒绝被转换为 NSMutableArray.

works fine so long as there are separators. I see that the method returns the original string wrapped in an NSArray if there isn't, though. This single element NSArray stubbornly refuses to be cast as an NSMutableArray.

但是,当我这样做时:

self.words = [NSMutableArray arrayWithArray:self.words];

它工作得很好.

我在这里遗漏了什么吗?从 NSArray 转换为 NSMutableArray 是不好的做法吗?

Is there something I'm missing here? Is it bad practice to cast from NSArray to NSMutableArray?

推荐答案

你很困惑.

此代码:

self.words = (NSMutableArray*)[self.text componentsSeparatedByString:@" "];

...是错误的,并且会让你在以后崩溃.Casting 只是告诉编译器相信我,我知道我在做什么."它不会改变底层对象的类型.方法 componentsSeparatedByString 返回一个 NSArray,而不是一个可变数组.如果您随后尝试改变结果数组,您将因无法识别的选择器消息而崩溃.通过强制转换,编译器相信您的对象在运行时确实是一个可变数组,但事实并非如此.

...is wrong, and is setting you up for a crash later on. Casting just tells the compiler "trust me, I know what I'm doing." It does not change the type of the underlying object. The method componentsSeparatedByString returns an NSArray, not a mutable array. If you then try to mutate the resulting array, you will crash with an unrecognized selector message. With the cast, the compiler trusts you that your object will really be a mutable array at runtime, but it will not be.

这会崩溃:

self.words = (NSMutableArray*)[self.text componentsSeparatedByString:@" "];
[self.words addObject: @"new"];

但是,这段代码:

self.words = [[self.text componentsSeparatedByString:@" "] mutableCopy];
[self.words addObject: @"new"];

...做正确的事.它不转换指针,它是对将 NSArray 作为输入并返回具有相同内容的可变数组的方法的方法调用.因此,第二行将起作用,因为第一行采用它从 componentsSeparatedByString 返回的不可变数组,并使用它来创建一个可变数组.

...does the right thing. It doesn't cast a pointer, it is a method call to a method that takes an NSArray as input and returns a mutable array with the same contents. Thus the second line will work because the first line takes the immutable array it gets back from componentsSeparatedByString and uses it to create a mutable array.

这篇关于为什么有时可以将 NSArray 转换为 NSMutableArray,有时不能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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