问题描述
我试图使用 NSRange
来保存一系列年份,例如
I'm trying to use NSRange
to hold a range of years, such as
NSRange years = NSMakeRange(2011, 5);
我知道 NSRange
,但我想循环的范围内的元素。这是可能的,而不将 NSRange
转换为 NSArray
?
I know NSRange
is used mostly for filtering, however I want to loop over the elements in the range. Is that possible without converting the NSRange
into a NSArray
?
推荐答案
这听起来像你期望 NSRange
像Python 范围
object。不是; 只是一个结构
It kind of sounds like you're expecting NSRange
to be like a Python range
object. It's not; NSRange
is simply a struct
typedef struct _NSRange {
NSUInteger location;
NSUInteger length;
} NSRange;
不是对象。一旦你创建了一个,你可以使用它的成员在一个普通的为
循环:
not an object. Once you've created one, you can use its members in a plain old for
loop:
NSUInteger year;
for(year = years.location; year < NSMaxRange(years); year++ ){
// Do your thing.
}
(仍然在假设你在想Python) ObjC中的语法称为对 NSArray
的内容进行迭代,这与Python for
循环很相似,但是由于文字和原始数字可以不能放入 NSArray
,你不能直接从 NSRange
到Cocoa数组。
(Still working on the assumption that you're thinking about Python.) There's syntax in ObjC called fast enumeration for iterating over the contents of an NSArray
that is pleasantly similar to a Python for
loop, but since literal and primitive numbers can't be put into an NSArray
, you can't go directly from an NSRange
to a Cocoa array.
类别可以使得更容易:
@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 fast enumeration:
NSArray * years = [NSArray WSSArrayWithNumbersInRange:NSMakeRange(2011, 5)];
for( NSNumber * yearNum in years ){
NSUInteger year = [yearNum unsignedIntegerValue];
// and so on...
}
这篇关于使用NSRange循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!