Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

GorillaPaws

macrumors 6502a
Original poster
Oct 26, 2003
932
8
Richmond, VA
This is a concept that I'm still a little fuzzy on, and have never really completely understood. When is it appropriate for methods to return (void)?

I was looking at the NSMutableSet methods and was specifically thinking about the -(void) unionSet: and the -(void) minusSet: methods. So why don't these methods return an (id) which would be the resulting NSMutableSet object?

If I were writing a method for the addition of two integers, I would expect an (int) result, so when I essentially add two NSMutableSet objects with a unionSet: method why does it not return anything? To me it's not intuitive at all, is there a rule of thumb that I'm forgetting?
 

autorelease

macrumors regular
Oct 13, 2008
144
0
Achewood, CA
A method should return void if it has side-effects, this includes modifying self in some way.

unionSet: and minusSet: don't return the resulting set because self is the resulting set. These methods operate on self and a second object and update self with the result.

So [set1 unionSet:set2] takes all the elements in set2 not in set1 and puts them in set1. [set1 minusSet:set2] takes all the elements in both set1 and set2 and removes them from set1. And so on. These are mutator methods, which is why they're in the NSMutableSet class. I can see how you could get confused, the names don't really imply that an action is being taken.

Unfortunately Cocoa doesn't have class methods like +[NSMutableSet unionOfSet1:withSet2:] that would return the result as an autoreleased object. (which is what you'd like) But that's what categories are for! :p
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.