• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Instance methods VS. Class methods
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Instance methods VS. Class methods


  • Subject: Re: Instance methods VS. Class methods
  • From: Andreas Monitzer <email@hidden>
  • Date: Sat, 24 Nov 2001 08:51:37 +0100

On Saturday, November 24, 2001, at 05:19 , Matt Ronge wrote:

I've read through Apple's docs, read through Learning Cocoa, and I have
searched all over the web. Yet none of them have shed light on the
difference between instance methods and class methods?

Can someone give examples of why you would use one over the other? Is there
something comparable in C++ to them? Is one of them just a private method
identifer for use internally by the class?

For newbies coming from C++ (like I was once), it's best compared to the reserved C++-word "static".

However, it's not really that way. In ObjC, there's one object per class that is automatically generated and the one responsible to create instances of the class.

So you can call [NSString alloc], since "alloc" is a class method. You can't call [NSString init], because "init" is an instance method and NSString is a class object.

The following is valid code (but results in a warning for whatever reason):

@interface MyObject: NSObject {
int value;
}

+ (void)initialize;
@end

@implementation MyObject

+ (void)initialize {
value=10;
}

@end

Since that class object is full-blown, you can use the variables. It's even possible to do the following:

+ (id)newInstance {
self=[[self alloc] init]; // replace self with a new instance
value=20; // set the value of the new instance
return [self autorelease];
}

But don't think about using that in production code :)

andy


  • Follow-Ups:
    • Re: Instance methods VS. Class methods
      • From: Ondra Cada <email@hidden>
    • Re: Instance methods VS. Class methods
      • From: Mike Shields <email@hidden>
References: 
 >Instance methods VS. Class methods (From: Matt Ronge <email@hidden>)

  • Prev by Date: Fw: DOcument Icons
  • Next by Date: Re: Instance methods VS. Class methods
  • Previous by thread: Re: Instance methods VS. Class methods
  • Next by thread: Re: Instance methods VS. Class methods
  • Index(es):
    • Date
    • Thread