有没有办法强制在 NSArray、NSMutableArray 等上打字? [英] Is there any way to enforce typing on NSArray, NSMutableArray, etc.?

查看:34
本文介绍了有没有办法强制在 NSArray、NSMutableArray 等上打字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以创建一个 NSMutableArray 实例,其中 all 元素的类型为 SomeClass?

Can I make a NSMutableArray instance where all the elements are of type SomeClass?

推荐答案

您可以使用 -addSomeClass: 方法创建一个类别以允许编译时静态类型检查(因此编译器可以让您知道如果您尝试添加一个对象,它知道它通过该方法知道是一个不同的类),但是没有真正的方法来强制数组只包含给定类的对象.

You could make a category with an -addSomeClass: method to allow compile-time static type checking (so the compiler could let you know if you try to add an object it knows is a different class through that method), but there's no real way to enforce that an array only contains objects of a given class.

一般来说,Objective-C 中似乎不需要这样的约束.我想我从未听说过有经验的 Cocoa 程序员希望使用该功能.唯一似乎是来自其他语言的程序员仍在用这些语言思考的人.如果您只想要数组中给定类的对象,则只在其中粘贴该类的对象.如果您想测试您的代码是否正常运行,请对其进行测试.

In general, there doesn't seem to be a need for such a constraint in Objective-C. I don't think I've ever heard an experienced Cocoa programmer wish for that feature. The only people who seem to are programmers from other languages who are still thinking in those languages. If you only want objects of a given class in an array, only stick objects of that class in there. If you want to test that your code is behaving properly, test it.

这篇关于有没有办法强制在 NSArray、NSMutableArray 等上打字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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