开发者

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 开发者_Python百科and expect a return of NSDictionary, or should I update a variable in memory and return void.


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


The question is confusing as stated. If they are properties then you have accessor methods that usually include something like:

-(void) setMyValue: (NSString*) inNewValue;
-(NSString*) myValue;

but it seems like you are probably asking something else since these can be dynamically synthesized for you by the compiler... So try rephrasing the question and we'll try again to help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜