E 'sorta di suona come vi aspettate NSRange
ad essere come un range
oggetto Python. Non è; NSRange
è semplicemente una struct
typedef struct _NSRange {
NSUInteger location;
NSUInteger length;
} NSRange;
non un oggetto. Dopo aver creato uno, è possibile utilizzare i suoi membri in una pianura vecchio for
ciclo:
NSUInteger year;
for(year = years.location; year < NSMaxRange(years); year++){
// Do your thing.
}
(ancora lavorando sul presupposto che si sta pensando di Python.) C'è sintassi objC chiamato fast enumeration per iterare su il contenuto di un NSArray
che è piacevolmente simile a un loop Python for
, ma poiché i numeri letterali e primitivi non possono essere inseriti in un NSArray
, non è possibile passare direttamente da un NSRange
a un array Cocoa.
Una categoria potrebbe fare che facile, però:
@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;
}
Quindi è possibile creare un array e utilizzare l'enumerazione veloce:
NSArray * years = [NSArray WSSArrayWithNumbersInRange:NSMakeRange(2011, 5)];
for(NSNumber * yearNum in years){
NSUInteger year = [yearNum unsignedIntegerValue];
// and so on...
}
fonte
2011-11-30 04:10:29
grazie, troppo male non c'è supporto per l'enumerazione veloce per NSRange. potrebbe salvarmi un po 'di tempo e code line – aporat
@manroe: Apprezzo la tua correzione del mio errore di codifica, ma il grande blocco "EDIT:" era inappropriato; potrebbe essere stato un commento, il riassunto della modifica, o davvero lasciato fuori del tutto. –