views:

60

answers:

4

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?

+3  A: 
[NSValue valueWithRange:r];

and get it back out with:

NSRange r = [rangeObject rangeValue];
mipadi
+5  A: 

Use NSValue's +valueWithRange:.

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

NSRange r = [[a objectAtIndex:4] rangeValue];
KennyTM
+2  A: 

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.

James Huddleston
Upvoting because this is clever and useful, but NSValue seems less elbowy. Thanks. :)
Steven Fisher
Thanks! I just learned about `NSValue` myself from the other answers (thanks @mipadi 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.
James Huddleston
+1  A: 

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

Mike Abdullah