NSArray 乘以每个参数

发布于 2024-08-28 17:23:19 字数 396 浏览 3 评论 0原文

有没有办法将数组中包含的每个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

好多鱼好多余 2024-09-04 17:23:19

不容易,不。您必须遍历整个过程,并将 NSNumber 的所有实例替换为 NSNumber 的新实例(NSNumber 本身是不可变的)。因此,例如:

for( int i = 0; i < [vertex count]; i++ )
  [vertex replaceObjectAtIndex:i withObject:[NSNumber numberWithFloat:[[vertex objectAtIndex:i] floatValue] * 10.0f]];

显然这很难阅读。如果您要经常操作它们(例如,对它们应用转换),那么最好只使用常规的原始浮点数组。

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:

for( int i = 0; i < [vertex count]; i++ )
  [vertex replaceObjectAtIndex:i withObject:[NSNumber numberWithFloat:[[vertex objectAtIndex:i] floatValue] * 10.0f]];

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).

海之角 2024-09-04 17:23:19

简短的回答 - 不。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文