Type of class in a NSMutableArray [duplicate]

百般思念 提交于 2019-11-28 06:18:42

问题


Possible Duplicate:
Is there any way to enforce typing on NSArray, NSMutableArray, etc.?

I'm Java programmer and I'm starting on Obj-C, in java i can create a mutable array with determined type of class, like as follow:

ArrayList<MyClass> list;

in Obj-c I know the NSMutableArray but i don't know and not found how to determinate the type of class into it.

Have a way of make this with it or other class without NSMutableArray which can do this?

Thanks a lot.


回答1:


No, Cocoa/Objective-C doesn't offer typed collections like this. All objects in the collection must inherit from NSObject (which is basically everything besides primitives and structs), but beyond that, it's up to you to understand/manage what is going on in the array. Objects in an NSMutableArray are represented in its interface by the generic type id.


From a design standpoint, collections in Cocoa typically do contain homogeneously-typed objects. The name of the array is often used to indicate what's inside it (just as in Java), e.g. bookTitlesArray or just bookTitles (i.e. strings). Additionally, from an abstraction standpoint, sometimes lightweight classes are used to "wrap" a raw NSMutableArray to enforce type checking at the interface. As in, a new class called BookTitleList which offered a subset of the add, lookup, remove methods and passed them through to an internal array after e.g. validation. But YMMV depending on your needs.




回答2:


Although there are no type parameters in Objective C, you'll find it much less of a nuisance than in Java because you don't have to downcast to call a method. Objective C is more like JavaScript in this respect.



来源:https://stackoverflow.com/questions/13093360/type-of-class-in-a-nsmutablearray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!