计算 id内的元素数量
我有一个 id
NSFastEnumeration 实现的唯一方法是:
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len
该方法返回我正在寻找的计数,但由于我不想真正枚举我想知道的对象,所以我可以安全地作为参数传递什么。只传递 nil,nil,0 可以吗?如果没有,我应该通过什么?
背景:
我想创建一个函数返回值的 NSArray,我想用给定集合中的每个元素调用它。我想要一个用函数枚举集合的结果数组。
id<NSFastEnumeration> enumeratable = someObject;
NSMutableArray* results = [NSMutableArray arrayWithCapacity:(#Fill in count here#)];
for (id object in enumeratable) {
[results addObject:callFunctionOnObject(object)];
}
如您所见,我只需要计数来优化数组初始化。我很清楚我可以使用 NSMutableArray* results = [NSMutableArray array]; 来代替。
I have an id<NSFastEnumeration>
object. I want to count the elements inside the object. How can that be achieved?
The only method NSFastEnumeration implements is:
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len
This method returns the count I am looking for, but as I do not want to really enumerate the objects I wonder, what I could safely pass in as arguments. Would it be OK to just pass nil,nil,0? If not, what should I pass?
The Background:
I want to create an NSArray of the return values of a function, which I want to call with every element in the given collection. I want an Array of the results of enumerating a collection with a function.
id<NSFastEnumeration> enumeratable = someObject;
NSMutableArray* results = [NSMutableArray arrayWithCapacity:(#Fill in count here#)];
for (id object in enumeratable) {
[results addObject:callFunctionOnObject(object)];
}
AS you can see I only need the count to optimize Array initialization. I am pretty aware that I could use NSMutableArray* results = [NSMutableArray array];
instead.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从 NSFastEnumeration 获取长度的唯一方法是循环遍历它。
当然,这意味着
枚举器
将耗尽并且您无法再次循环它。此外,容量只是一个提示。设置它没有什么好处。
The only way to get the length from an NSFastEnumeration is to loop through it.
Of course this means the
enumerator
will be exhausted and you can't loop it again.Also, the capacity is just a hint. There's little benefit in setting it.