使用 NSRange 循环
我正在尝试使用 NSRange
来保存一系列年份,例如
NSRange years = NSMakeRange(2011, 5);
我知道 NSRange
主要用于过滤,但是我想循环该范围内的元素。如果不将 NSRange
转换为 NSArray
,这可能吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
听起来好像您期望
NSRange
就像 Pythonrange
对象一样。它不是;NSRange
只是一个结构体而不是对象。一旦创建了一个,您就可以在普通的旧
for
循环中使用其成员:(仍然假设您正在考虑 Python。)ObjC 中有一种名为 快速枚举用于迭代
NSArray
的内容与 Pythonfor
循环非常相似,但由于文字和原始数字不能放入NSArray
,您不能直接从NSRange
转到 Cocoa 数组。不过,类别可以使这变得更容易:
然后您可以创建一个数组并使用快速枚举:
It kind of sounds like you're expecting
NSRange
to be like a Pythonrange
object. It's not;NSRange
is simply a structnot an object. Once you've created one, you can use its members in a plain old
for
loop:(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 Pythonfor
loop, but since literal and primitive numbers can't be put into anNSArray
, you can't go directly from anNSRange
to a Cocoa array.A category could make that easier, though:
Then you can create an array and use fast enumeration:
请记住,NSRange 是一个包含两个整数的结构,表示范围的开始和长度。您可以使用 for 循环轻松循环所有包含的整数。
Remember that a NSRange is a structure holding two integers, representing the start and length of the range. You can easily loop over all of the contained integers using a for loop.
这是一个有点老的问题,但是使用
NSArray
的替代方法是创建一个具有所需范围的NSIndexSet
(使用indexWithIndexesInRange:
> 或initWithIndexesInRange:
),然后使用块枚举,如 https://stackoverflow.com/a/4209289/138772。 (似乎相关,因为我自己刚刚检查过这一点。)This is a bit of an old question, but an alternative to using an
NSArray
would be to create anNSIndexSet
with the desired range (usingindexWithIndexesInRange:
orinitWithIndexesInRange:
) and then using block enumeration as in https://stackoverflow.com/a/4209289/138772. (Seemed relevant as I was just checking on this myself.)我的替代解决方案是定义一个宏,以使速记更快。
要称呼它,您可以这样做:
就我个人而言,我仍在尝试弄清楚如何编写宏,以便我可以这样称呼它:
尚不支持...希望可以帮助或使您更快地输入程序
My alternate solution for this, was to define a macro just to make shorthand quicker.
To call it you do:
personally I am still trying to figure out how I can write the macro so I can just call it like:
which is not supported just yet... hope that helps or makes typing your program quicker