从 Objective-C 中的方法返回多个对象
我有一个方法,它接受 NSMutableArray 作为参数,我希望它返回该数组、该方法中创建的另一个数组以及该方法创建的 int 。我意识到这可以通过创建一个包含所有这些对象的数组并返回该数组,然后将它们从方法外部的数组中删除来完成,但是还有其他方法可以返回多个对象吗?
I have a method that takes an NSMutableArray as a parameter, and I would like it to return that array, another array that is created in the method, and an int created by the method. I realize this could be done by making an array that had all these objects in it, and returning that, then removing them from the array outside the method, but is there another way to return multiple objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
传回多个值的典型方法是:
通过这种方式)
NSDictionary 或自定义类
以上对于许多情况来说都是很好的解决方案,但这里是另一个在其他情况下可能效果最好的解决方案: 在
您的方法中添加一个块:
然后使用这样的方法:
上例中的返回对象仅是可在块内使用,因此如果您想将它们保留在块外使用,只需设置一些 __block 变量即可。
The typical ways to pass back multiple values are to:
this way)
NSDictionary or a custom class
The above are good solutions for many situations, but here is another solution that may work best in other situations:
Add a block to your method:
Then use the method like this:
The return objects in the above example are only usable within the block, so if you want to keep them around for use outside the block, just set some __block vars.
使用
NSDictionary
返回多个值是 Obj-C 中执行此操作的惯用方法。方法签名看起来像这样:
并且您将需要在适当的文件中定义字典键。
与使用数组相比的优点是元素的顺序和元素的存在/不存在并不重要,如果您想返回其他对象,则将来更容易扩展。它也比通过引用传递更加灵活和可扩展。
Using an
NSDictionary
to return multiple values is the customary way to do this in Obj-C.The method signature would look something like this:
and you are going to want to define your dictionary keys in the appropriate files.
The advantage over using an array is that the the order of elements and the presence/absence of elements doesn't matter, making it far easier to extend in the future, if you want to return additional objects. It's also far more flexible and extensible than passing by reference.
另一种方法是让用户传递一个他们想要用来保存数据的指针。下面是一个示例,它返回一个数组并使用指针为您提供一个 int 值和另一个数组。编辑好,这是我自己刚刚测试过的工作版本:
这样你就可以这样说:
它基本上就像退货一样!
Another way you can do it is have the user pass a pointer which they want to use to hold the data. Here is a sample that returns an array and uses pointers to give you an int value and another array. EDIT ok here is the working version I just tested it myself:
That way you could say like:
And it basicly works like a return!
您可能需要考虑返回一个结构。
您的方法现在看起来像这样:
您可以像这样使用它:
希望有所帮助。 ;)
You might want to consider returning a struct.
Your method could now look like this:
And you'd use it like:
Hope that helped. ;)