Search code examples
objective-cpropertiesreturnself

Is it best to return NSArray or void and update self property?


I am working on a delegate class that controls several views, and find myself switching between updating properties in the delegate and returning values from methods. What is the proper way to do this?

-(NSArray)blah{ return myarray; }

or -(void)blah{ [self myarray:value] }

--------------- Clarification of question below

if I have a helper method that converts an NSArray into a NSDictionary should I call my helper method and expect a return of NSDictionary, or should I update a variable in memory and return void.


Solution

  • There's a case for each approach, depending on what you are really doing. The two choices are:

    • It is truly a helper method, that has use in many places in your application.
    • It is specific to a single class and the dictionary is a member of that class.

    OPTION 1) If it is truly a helper method, I believe that you should return the NSDictionary from the method. I'm assuming it is newly allocated within that method.

    In other words, prefer:

    + (NSDictionary *) dictFromArray:(NSArray *);
    

    If it has utility outside of a single class, you could put it in a sensible class that collects related utility methods.

    The alternative approach of passing in an empty dictionary to be filled is practiced in C because it creates symmetry around allocating and freeing and makes it clear who owns the memory.

    In Objective-C, reference counting takes care of that, so you can avoid the extra code of allocating empty objects just to call the method.

    For example:

    NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];
    dictFromArray(myArray, myDict);
    

    When it comes to knowing who owns the object, you should stick to Objective-C conventions, where:

    + (NSDictionary *) dictFromArray:(NSArray *)array
    

    returns an autorelease object, so the caller knows they need to retain it if they want to hold a reference.

    OPTION 2) If the functionality is specific to a single class and that class has the dictionary as a member, then I would pass in the array, update the dictionary member variable using the array contents, and return void.

    Something like:

    - (void) setBlahFromArray:(NSArray *)array