Ant
Ant

Reputation: 1708

What's the best way to return 2 results from a method

I have a method that returns an integer and I now also want to return a small struct or class. If I was using C++ I would pass a reference to the struct in as a parameter. In iOS using ARC, I think the equivalent is to use a pointer to a pointer that has the __autoreleasing attribute which I find a bit cumbersome.

I could return an array containing the two values but then think I would be alloc'ing more than necessary and I could be using this a lot (100,000 calls).

Upvotes: 0

Views: 125

Answers (2)

MechEthan
MechEthan

Reputation: 5703

Even with ARC, you can just pass in a struct by reference or an object pointer...

Pass the struct by ref just like you would in C++, e.g. &aStruct

-(int)getStuffOut:(SomeStruct *)aStruct {
   if(!aStruct) {
      return 0;
   }
   aStruct->myInt = 12345;
   aStruct->myFloat = 12.345f;
   return 1;
}

Or:

-(int)getStuffOut:(SomeClass *)anObject {
   if(!anObject) {
      return 0;
   }
   anObject.myIntProperty = 12345;
   anObject.myFloatProperty = 12.345f;
   return 1;
}

Upvotes: 3

Ecarrion
Ecarrion

Reputation: 4950

If you're using ARC you dont have to worry about memory management if you're using plain Objective-C.

Custom objects are passed by reference, so you can pass your OBJ-C object to your method and fill your stuff in.

Or you can return a Struct that holds the two values

+(struct YourStruct)someMethod:(NSString *)someParam;

+(YourStruct)someMethod:(NSString)someParam {

    //some method code

    YourStruct st;

    //Do something here with the struct

    return st;
}

Upvotes: 0

Related Questions