开发者

count elements inside id<NSFastEnumeration>

开发者 https://www.devze.com 2023-01-09 23:15 出处:网络
I have an id<NSFastEnumeration> object. I want to count the elements inside the object. How can that be achieved?

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:

- (NSUI开发者_JAVA百科nteger)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.


The only way to get the length from an NSFastEnumeration is to loop through it.

int count = 0;
for (id x in enumerator)
  ++ count;
return count;

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消