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

4

59

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?

Emelineemelita answered 22/10, 2010 at 17:2 Comment(0)
D
143

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

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

NSRange r = a[4].rangeValue;
Dinnerware answered 22/10, 2010 at 17:5 Comment(4)
Why NSValue could store NSRange but NSArray could not?Roundly
Because NSArray can store objects only. NSRange is not an object, but you can wrap it with NSValue so it can be used by NSArray, NSDictionary etc.Gastrulation
while iterating through NSMutable array , NSRange r = a[i].rangeValue giving error like property range value not found on type id...Mariel
@jayantrawat: The type of the array a should be generic: NSMutableArray<NSValue*>*.Dinnerware
M
13
[NSValue valueWithRange:r];

and get it back out with:

NSRange r = [rangeObject rangeValue];
Monopolize answered 22/10, 2010 at 17:5 Comment(1)
what is rangeobject?Mariel
A
5

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.

Alex answered 22/10, 2010 at 17:6 Comment(2)
Upvoting because this is clever and useful, but NSValue seems less elbowy. Thanks. :)Emelineemelita
Thanks! I just learned about NSValue myself from the other answers (thanks @Monopolize and @KennyTM), and it's definitely less elbowy than my suggestion. To be more deserving of your kind upvote, I updated my answer to mention that the string version can be useful with storing ranges in property lists.Alex
G
4

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

Gobbledygook answered 22/10, 2010 at 23:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.