简体   繁体   English

如何实现自定义对象,如NSArray

[英]How to implement custom object like NSArray

I want to implement an object named "XXXList" which will return a collection (not NSArray subclass), so that I can use it like an NSArray: 我想实现一个名为“ XXXList”的对象,该对象将返回一个集合(不是NSArray子类),以便可以像NSArray一样使用它:

XXXList *list = [XXXList list];

for(id object in list)
{
    ......
}

There are several things you can do with NSArray s, I'll list the two of them that I think might be what you're after: 您可以使用NSArray做几件事,我将列出其中的两点,我认为这可能是您追求的目标:

Firstly you can iterate with a for…in loop ( NSFastEnumeration ), secondly you can use the indexed subscript notation (something like list[2] ). 首先,您可以使用for…in循环( NSFastEnumeration )进行迭代,其次,您可以使用索引下标表示法(类似于list[2] )。 Fortunately, both of these are available for other types of objects as well, you just need to implement them. 幸运的是,这两个对象也可用于其他类型的对象,您只需要实现它们即可。

Implementing NSFastEnumeration isn't so trivial, I'd suggest reading up on Mike Ash's NSBlog post . 实施NSFastEnumeration并非易事,我建议阅读Mike Ash的NSBlog帖子

Implementing subscript notation on the other hand is quite simple, there are just two methods you need to implement. 另一方面,实现下标表示法非常简单,只需实现两种方法即可。

There's the getter: 有吸气剂:

 - (id)objectAtIndexedSubscript: (NSUInteger)index;

and the setter 和二传手

 - (void)setObject: (id)obj atIndexedSubscript: (NSUInteger)index;

There's an NSBlog post on that , too. 也有关于此的NSBlog帖子

如果要使用自己的类,则需要实现NSFastEnumeration

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM