Note that there are some explanatory texts on larger screens.

plurals
  1. POFollowup on: Difference between class methods and instance methods?
    primarykey
    data
    text
    <p>This is a followup question to (user) micmoo's response on <a href="https://stackoverflow.com/questions/1053592/objective-c-class-vs-instance-methods">What is the difference between class and instance methods?</a> .</p> <p>If I change the variable: numberOfPeople from static to a local variable in the class, I get numberOfPeople as 0. I have also added a line to show the numberOfPeople after the variable has been incremented each time. Just to avoid any confusion, my code is as follows:</p> <pre><code>// Diffrentiating between class method and instance method #import &lt;Foundation/Foundation.h&gt; // static int numberOfPeople = 0; @interface MNPerson : NSObject { int age; //instance variable int numberOfPeople; } + (int)population; //class method. Returns how many people have been made. - (id)init; //instance. Constructs object, increments numberOfPeople by one. - (int)age; //instance. returns the person age @end @implementation MNPerson int numberOfPeople = 0; - (id)init{ if (self = [super init]){ numberOfPeople++; NSLog(@"Number of people = %i", numberOfPeople); age = 0; } return self; } + (int)population{ return numberOfPeople; } - (int)age{ return age; } @end int main(int argc, const char *argv[]) { @autoreleasepool { MNPerson *micmoo = [[MNPerson alloc] init]; MNPerson *jon = [[MNPerson alloc] init]; NSLog(@"Age: %d",[micmoo age]); NSLog(@"Number Of people: %d",[MNPerson population]); } } </code></pre> <p>Output:</p> <p>In init block. Number of people = 1 In init block. Number of people = 1 Age: 0 Number Of people: 0</p> <p>Case 2: If you change the numberOfPeople in the implementation to 5 (say). The output still does not make sense.</p> <p>Thank you in advance for your help.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload