Reg*_*an 5 methods objective-c return-value
我有一个方法,它将NSMutableArray作为参数,我希望它返回该数组,在该方法中创建的另一个数组,以及由该方法创建的int.我意识到这可以通过制作一个包含所有这些对象的数组,并返回它,然后从方法外的数组中删除它们来完成,但是有另一种方法可以返回多个对象吗?
传递多个值的典型方法是:
以上是许多情况下的好解决方案,但这是另一种在其他情况下可能效果最佳的解决方案:
在方法中添加一个块:
- (void)myMethodWithMultipleReturnObjectsForObject:(id)object returnBlock:(void (^)(id returnObject1, id returnObject2))returnBlock
{
// do stuff
returnBlock(returnObject1, returnObject2);
}
Run Code Online (Sandbox Code Playgroud)
然后使用这样的方法:
[myMethodWithMultipleReturnObjectsForObject:object returnBlock:^(id returnObject1, id returnObject2) {
// Use the return objects inside the block
}];
Run Code Online (Sandbox Code Playgroud)
上例中的返回对象只能在块中使用,因此如果要保留它们以便在块外使用,只需设置一些__block变量即可.
// Keep the objects around for use outside of the block
__block id object1;
__block id object2;
[myMethodWithMultipleReturnObjectsForObject:object returnBlock:^(id returnObject1, id returnObject2) {
object1 = returnObject1;
object2 = returnObject2;
}];
Run Code Online (Sandbox Code Playgroud)
使用a NSDictionary来返回多个值是在Obj-C中执行此操作的常用方法.
方法签名看起来像这样:
-(NSDictionary *)doSomeStuffThatReturnsMultipleObjects;
Run Code Online (Sandbox Code Playgroud)
并且您将要在相应的文件中定义字典键.
// Header File
extern NSString *const JKSourceArray;
extern NSString *const JKResultsArray;
extern NSString *const JKSomeNumber;
// Implementation File
NSString *const JKSourceArray = @"JKSourceArray";
NSString *const JKResultsArray = @"JKResultsArray";
NSString *const JKSomeNumber = @"JKSomeNumber";
Run Code Online (Sandbox Code Playgroud)
使用数组的优点是元素的顺序和元素的存在/不存在无关紧要,如果您想要返回其他对象,将来更容易扩展.它比通过引用传递更灵活和可扩展.