0

I am developing an API that returns an NSData to the caller. I need the object to be provided in the function parameters (not as a return value). Which of the approach below is preferred and why?

NSData* data;
[self foo1:&data];

-(BOOL)foo1:(NSData**)data {
  *data = [@"1234" dataUsingEncoding:NSUTF8StringEncoding];
  ...
}

or

NSMutableData* data = [[NSMutableData alloc] init];
[self foo2:data];

-(BOOL)foo2:(NSMutableData*)data {
  [data setData:[@"1234" dataUsingEncoding:NSUTF8StringEncoding]];
}
liorco
  • 1,483
  • 1
  • 9
  • 12
  • 1
    Out of curiosity, why can't you use a return value (and return `nil` on failure, if necessary)? It's better than both of the above options. – Rob May 29 '17 at 08:27
  • `foo2` is suitable when the method appends data. I would do `- (NSData *)foo3` and return `nil` instead of `NO`. – Willeke May 29 '17 at 08:40
  • I know that the best approach is to return the NSData. However, I am not able to return the NSData object since in the real API it return something else there (the major data of the API) the NSData I need is kind of minor additional data (that might be nil/empty). So Assuming this must be passed as a parameter which approach is preferred? – liorco May 29 '17 at 08:49
  • 1
    You should have put this information in the question. Use `NSMutableData*` if the method adds data, use `NSData**` if the method creates the data. Or return a custom object with data and minorData properties. – Willeke May 29 '17 at 10:41

2 Answers2

1

The better is asynchronous response:

- (void)fooWithCompletion:(void (^)(NSData *responseData, NSError *responseError))completion;
Cy-4AH
  • 4,370
  • 2
  • 15
  • 22
  • 1
    There is nothing in OP's question that indicates any kind of an expensive or blocking operation is being used to generate the data. If the data is already available when the method is called, there is no reason to add this complexity. – bbum May 29 '17 at 14:10
0

Thanks @Willeke. I am going to adopt your advice - Use NSMutableData* if the method adds data, use NSData** if the method creates the data.

liorco
  • 1,483
  • 1
  • 9
  • 12