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

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

问题描述

我可以创建一个NSMutableArray,其中所有元素的类型是SomeClass?

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

推荐答案

code> -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天全站免登陆