2

I am used to functional programming. Now writing for iOS I find myself using class methods (+) frequently, rather than creating instances (from -).

Usually I use class methods for small, recurring tasks - like sending async requests, updating database, storing/retrieving preferences etc.

Is this the right thing to do, or should I try to change my thinking more and start using instances instead? Is it even possible to avoid using class methods all together?

selytch
  • 535
  • 2
  • 9
  • 24

3 Answers3

4

My best recommendation would be to look at how Foundation and Cocoa is doing and do it similarly. There is a place for class methods in Objective-C.

Some examples of class methods include

[UIView animateWithDuration:0.3 animations:^{
    // Animation here...
}];

and

[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *date, NSError *error) {
                           // Handle response here ...
                       }];
David Rönnqvist
  • 56,267
  • 18
  • 167
  • 205
  • Those are more of convenience methods and initializers (especially the animation one) than tried and true class methods, but I see your point. +1 – CodaFi Mar 03 '13 at 17:16
2

There is a third alternative supported by Objective C for encapsulating functionality that does not need implicit access to instance variables - it is using "plain" C functions. Unlike class functions, "plain" C functions do not use virtual dispatch, which may be important in vary tight loops.

Note that class methods provide more functionality than, say, static methods of Java, C++, and C#: they support overriding, letting class method in base classes use more specific implementations in derived classes.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Class methods are used when you do not need any instance of the class, and your purpose gets served only by a method call of that like [[NSUserDefaults standardUserDefaults] synchronize];


In MRC

The alloc/init combination gives you an owning reference. That means you must release it later on. The classMethod returns a non-owning reference. You may not release it.

i.e.,

Person *firstPerson=[Person personWithName:@"AnoopVaidya" address:@"India"];

In ARC, for the above there is not such differnce.

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
  • 1
    I would say that class methods serve a far broader purpose than that. I can, for instance, make a little "singleton" out of a static variable and make the class method an accessor. – CodaFi Mar 03 '13 at 17:15
  • @CodaFi: Yes that should be in Answer :) – Anoop Vaidya Mar 03 '13 at 17:16