2

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)
{
    ......
}
9
  • where will XXXList will store values? if not array then how? Commented May 30, 2013 at 10:08
  • @AnoopVaidya, obviously an object that implements the NSFastEnumeration protocol… Commented May 30, 2013 at 10:13
  • @ikinciviking: I agree. But I would like to know how can I create a set of objects which are not arrays/set/dictionary. HOw to add:, remove: etc. Commented May 30, 2013 at 10:24
  • 1
    @AnoopVaidya: in the context of this question that is irrelevant. Commented May 30, 2013 at 10:26
  • @AnoopVaidya (Short answer: You could build a data structure (array or linked list) with pure C constructs and then create an objective-c wrapper class around that.) I think you pose a valid question. Why don’t you try to open a new one? Commented May 30, 2013 at 13:34

2 Answers 2

3

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.

3
  • OP says : "no nsarray and its subclass" Commented May 30, 2013 at 10:04
  • @AnoopVaidya I know, that’s why I listed two ways for objects to start behaving like NSArrays even though they’re not. Commented May 30, 2013 at 10:06
  • @AnoopVaidya, an object does not need to be an array to be enumeratable. Commented May 30, 2013 at 10:13
2

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.