Loop using NSRange

I am trying to use NSRange to store several years, for example

 NSRange years = NSMakeRange(2011, 5); 

I know that NSRange is mainly used for filtering, however I want to NSRange over elements in a range. Is this possible without converting NSRange to NSArray ?

+6
source share
4 answers

It looks like you expect NSRange be like a Python range object. Not this; NSRange is just a structure

 typedef struct _NSRange { NSUInteger location; NSUInteger length; } NSRange; 

not an object. Once you have created it, you can use its elements in a simple old for chain:

 NSUInteger year; for(year = years.location; year < NSMaxRange(years); year++ ){ // Do your thing. } 

(Still working on what you think of Python.) There, the syntax in ObjC is called a quick enumeration for repeating the contents of a NSArray , which nicely looks like a Python for loop, but since literals and primitive numbers cannot be placed in NSArray , you don’t can go directly from the NSRange array to Cocoa.

A category can make it easier:

 @implementation NSArray (WSSRangeArray) + (id)WSSArrayWithNumbersInRange:(NSRange)range { NSMutableArray * arr = [NSMutableArray array]; NSUInteger i; for( i = range.location; i < NSMaxRange(range); i++ ){ [arr addObject:[NSNumber numberWithUnsignedInteger:i]]; } return arr; } 

Then you can create an array and use a quick enumeration:

 NSArray * years = [NSArray WSSArrayWithNumbersInRange:NSMakeRange(2011, 5)]; for( NSNumber * yearNum in years ){ NSUInteger year = [yearNum unsignedIntegerValue]; // and so on... } 
+8
source

Remember that NSRange is a structure containing two integers representing the beginning and length of the range. You can easily iterate over all contained integers using the for loop.

 NSRange years = NSMakeRange(2011, 5); NSUInteger year; for(year = years.location; year < years.location + years.length; ++year) { // Use the year variable here } 
+6
source

This is a bit of an old question, but an alternative to using NSArray would be to create an NSIndexSet with the desired range (using indexWithIndexesInRange: or initWithIndexesInRange: , and then using a block enum, as in fooobar.com/questions/123567 / .... (I believe I was just checking it myself.)

+3
source

My alternative solution for this was to define a macro to speed up the reduction.

 #define NSRangeEnumerate(i, range) for(i = range.location; i < NSMaxRange(range); ++i) 

To call it, follow these steps:

 NSArray *array = @[]; // must contain at least the following range... NSRange range = NSMakeRange(2011, 5); NSUInteger i; NSRangeEnumerate(i, range) { id item = array[i]; // do your thing } 

personally, I'm still trying to figure out how I can write a macro, so I can simply call it the following:

 NSRangeEnumerate(NSUInteger i, range) { } 

which is not yet supported ... hope it helps to type your program faster

0
source

Source: https://habr.com/ru/post/902721/


All Articles