目标C - 子类NSArray [英] Objective C - Subclassing NSArray

查看:200
本文介绍了目标C - 子类NSArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图子类化 NSArray ,但它尝试访问计数方法时崩溃的应用程序。我知道 NSArray 是一个类群集

I am trying to subclass NSArray, but it crashes the app when trying to access the count method. I know that NSArray is a class cluster.



我知道我可以简单地子类 NSObject 并且有我的数组作为一个实例变量,但我宁愿子类 NSArray

I know that I can simply subclass NSObject and have my array as an instance variable but I would rather subclass NSArray.

EDIT:
原因:
我正在创建一个纸牌游戏, c $ c> Deck 它应该子类 NSMutableArray 有一些额外的方法( -shuffle -removeObjects: -renew 等),我认为它会看起来更干净的子类<$

Reason: I am creating a card game, I have a class Deck which should subclass NSMutableArray to have a couple of extra methods (-shuffle, -removeObjects:, -renew, etc), and I think it will look cleaner to subclass NSArray rather than having a var.

推荐答案

添加类别的问题类似这样的类是类的所有实例将继承附加的方法。这是没有必要的(因为不是每个阵列需要能够被洗牌等)和危险的(因为你不能从typechecking中获益,以确保你目前指的是NSArray是一个预期被改组)。

The problem with adding a category on a class like this is that all instances of the class will inherit the additional methods. That's both unnecessary (since not every array needs to be able to be shuffled, etc.) and dangerous (because you can't benefit from typechecking to be sure the NSArray you're currently referring to is really one that was expected to be shuffled).

另一种方法是创建你自己的Deck类,它有一个NSMutableArray作为实例变量。在那里你可以完全按照你想要的方式在你的套牌上定义动作,而你使用一个NSMutableArray的事实成为一个实现细节。这使您可以在编译期利用类型检查,它允许您更改Deck类的内部实现,而不更改其客户端。例如,如果你决定某种原因NSMutableDictionary将是一个更好的后备存储,你可以在你的Deck类的实现中做所有这些更改,而不改变任何创建和使用Deck的代码。

An alternative would be to create your own Deck class that has an NSMutableArray as an instance variable. There you can define actions on your deck exactly as you would like, and the fact that you are using an NSMutableArray becomes an implementation detail. This lets you take advantage of typechecking at compile-time and it lets you change the internal implementation of your Deck class without changing its clients. For instance, if you decided for some reason that an NSMutableDictionary would be a better backing store, you can make all those changes within the implementation of your Deck class without changing any of the code that creates and uses the Deck.

这篇关于目标C - 子类NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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