user2435956
user2435956

Reputation: 21

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 *list = [XXXList list];

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

Upvotes: 2

Views: 218

Answers (2)

Raphael Schweikert
Raphael Schweikert

Reputation: 18556

There are several things you can do with NSArrays, I’ll list the two of them that I think might be what you’re after:

Firstly you can iterate with a for…in loop (NSFastEnumeration), secondly you can use the indexed subscript notation (something like 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.

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.

Upvotes: 3

MarrLiss
MarrLiss

Reputation: 808

You need to implement NSFastEnumeration if you want to use your own classes.

Upvotes: 2

Related Questions