How do I store an NSRange in a NSMutableArray or other container?

Steven Fisher picture Steven Fisher · Oct 22, 2010 · Viewed 18.4k times · Source

Here's what I want to do:

NSRange r = NSMakeRange(0,5);
id a = [NSMutableArray a];
[a addObject: r]; // but NSRange is not a NSObject *

With a boolean, I'd use code like this:

[a addObject: [NSNumber numberWithBool: YES]];

or with an integer:

[a addObject: [NSNumber numberWithInteger: 3]];

So what's the equivalent with a NSRange? What I don't really want to do is create my own subclass of NSObject to accomplish this. Surely there's a way with what Apple's already provided?

Answer

kennytm picture kennytm · Oct 22, 2010

Use NSValue's +valueWithRange:. To retrieve the range structure back, use the property rangeValue.

[a addObject:[NSValue valueWithRange:r]];
...

NSRange r = a[4].rangeValue;