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

IphoneCocoaCocoa TouchNsobjectNsrange

Iphone Problem Overview


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?

Iphone Solutions


Solution 1 - Iphone

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

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

NSRange r = a[4].rangeValue;

Solution 2 - Iphone

[NSValue valueWithRange:r];

and get it back out with:

NSRange r = [rangeObject rangeValue];

Solution 3 - Iphone

If you need to store the NSRange in a property list, you can also turn an NSRange into an NSString using the NSStringFromRange function. And then, you can turn that string back into a range using the NSRangeFromString function.

Solution 4 - Iphone

One other option might be to add those ranges into an NSIndexSet, depending on how you intend to use them next.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSteven FisherView Question on Stackoverflow
Solution 1 - IphonekennytmView Answer on Stackoverflow
Solution 2 - IphonemipadiView Answer on Stackoverflow
Solution 3 - IphoneJames HuddlestonView Answer on Stackoverflow
Solution 4 - IphoneMike AbdullahView Answer on Stackoverflow