Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 367
Steven Fisher Avatar asked Oct 22 '10 17:10

Steven Fisher


People also ask

What is the key difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

What is NSMutableArray in objective C?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .

What is an NSArray?

NSArray creates static arrays, and NSMutableArray creates dynamic arrays. You can use arrays when you need an ordered collection of objects. NSArray is “toll-free bridged” with its Core Foundation counterpart, CFArrayRef . See Toll-Free Bridging for more information on toll-free bridging.

Is NSMutableArray ordered?

The answer is yes, the order of the elements of an array will be maintained - because an array is an ordered collection of items, just like a string is an ordered sequence of characters...


2 Answers

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

[a addObject:[NSValue valueWithRange:r]]; ...  NSRange r = a[4].rangeValue; 
like image 104
kennytm Avatar answered Nov 08 '22 07:11

kennytm


[NSValue valueWithRange:r]; 

and get it back out with:

NSRange r = [rangeObject rangeValue]; 
like image 31
mipadi Avatar answered Nov 08 '22 07:11

mipadi