NSArray 乘以每个参数
有没有办法将数组中包含的每个 NSNumber 乘以 10? 这是我到目前为止所拥有的:
NSMutableArray *vertex = [NSMutableArray arrayWithCapacity:3];
[vertex addObject:[NSNumber numberWithFloat:1.0]];
[vertex addObject:[NSNumber numberWithFloat:2.0]];
[vertex addObject:[NSNumber numberWithFloat:3.0]];
[vertex makeObjectsPerformSelector:@selector(doSomethingToObject:)];
我不确定使用什么选择器来执行此操作,请帮忙!
Is the there a way to multiply each NSNumber contained in the array by 10?
Here is what I have so far:
NSMutableArray *vertex = [NSMutableArray arrayWithCapacity:3];
[vertex addObject:[NSNumber numberWithFloat:1.0]];
[vertex addObject:[NSNumber numberWithFloat:2.0]];
[vertex addObject:[NSNumber numberWithFloat:3.0]];
[vertex makeObjectsPerformSelector:@selector(doSomethingToObject:)];
I am not sure what selector to use to do this, please help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不容易,不。您必须遍历整个过程,并将 NSNumber 的所有实例替换为 NSNumber 的新实例(NSNumber 本身是不可变的)。因此,例如:
显然这很难阅读。如果您要经常操作它们(例如,对它们应用转换),那么最好只使用常规的原始浮点数组。
Not easily, no. You would have to loop through the entire thing and replace all those instances of NSNumber with new instances of NSNumber (NSNumber itself is immutable). So, for example:
Obviously this is rather hard to read. You are probably better off just using a regular, primitive array of floats if you are going to be manipulating them often (e.g., applying transformations to them).
简短的回答 - 不。
NSNumber 只是原始值的容器。它不做任何数学工作。 makeObjectsPerformSelector 方法可用于告诉数组中的每个对象执行某些操作。但是每个对象的类都必须具有选择器所属的方法。 NSNumber 也没有提供任何改变存储值的方法。因此,即使您向 NSNumber 添加了一个类别来进行数学计算,您仍然需要用新计算的值替换数组中的旧值。
我认为更好的解决方案是向 NSMutableArray 添加一个类别方法来完成这项工作。它会查看内容,计算每个新值,然后用新值替换每个数组成员。
Short answer - no.
NSNumber of merely a container for a primitive value. It does not do any mathematical work. The makeObjectsPerformSelector method can be used to tell each object in the array to do something. But the class of each of those objects has to have the method the selector is for. NSNumber also does not provide any method for changing the stored value. So even if you added a category to NSNumber to do the math, you would still have to replace the old value in the array with the newly computed one.
I think a better solution would be to add a category method to NSMutableArray to do the work. It would look through the contents, calculate each new value and then replace each array member with the new one.