Spot the difference: instance methods and class methods in Xcode for iOS

In preparation for a forthcoming blogpost on self, super, polymorphism and inheritance in Xcode and iOS5, which has been inspired and informed by Matt Neuburg's book Programming iOS 5, I'm posting some sample code to illustrate the points that will be made. If you wish to experiment, then copy and paste this into your Xcode project.

Previous posts have mainly focused on instance methods, which we've used to manipulate objects. These are after all the most common type of methods we'll be calling. The other kind of method is the class method. The most common of which is the one used in the creation of instances: alloc.

We've also used yellowColor and blueColor they are class methods because they are called against UIColor.

An instance method is identified by the dash '-' that it begins with. Like so:


-(void)backgroundColorChange {
    [self setBackgroundColor:[UIColor blueColor]];
    }


Whereas a class method has a plus '+' sign at the beginning. Like this:


+(void)description {
    NSLog(@"Hello there, this is the SquareView Class!");
}

And to call the instance method we would write something like this:

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

SquareView *squareViewNew = [[SquareView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    [self.view addSubview:squareViewNew]; 
    [squareViewNew backgroundColorChange];
  
}

Whereas a class method is called like this:

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
  
    [SquareView description];  


}

Don't get confused by the fact that we're calling a class method against a subclass, because a (sub)class is a class like any other. UIView itself is a subclass of NSObject. So don't think there is any differentiation between (system) class and (sub) class because a class method doesn't make any discrimination between the two.

Comments

  1. A nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.

    iOS Training in Chennai

    ReplyDelete

Post a Comment