Objective C static class variables

后端 未结 4 815
悲哀的现实
悲哀的现实 2020-12-12 17:14

I am new to Objective C and am reading a book called \"Visual Quickstart Guide: Objective-C\" by Steven Holzner, Peachpit Press

In Chapter 6: Object Oriented Program

4条回答
  •  悲哀的现实
    2020-12-12 17:47

    I’ve seen one Visual Quickstart Guide about Unix and it sucked big time. This one does not seem to be much better, at least from the sample. The correct way to create a class variable in Objective-C looks like this:

    // Counted.h
    @interface Counted : NSObject
    
    + (NSUInteger) numberOfInstances;
    
    @end
    
    // Counted.m
    #import "Counted.h"
    
    static NSUInteger instances = 0;
    
    @implementation Counted
    
    - (id) init {
        …
        instances++;
        …
    }
    
    - (void) dealloc {
        instances--;
    }
    
    + (NSUInteger) numberOfInstances {
        return instances;
    }
    
    @end
    

    This is in fact a static variable, not a true class variable. But you should not worry about class variables too much anyway, they’re usually a sign that you’re doing something wrong. (I’m oversimplifying a bit, but not much.)

    If you’re looking for a decent Objective-C book, read the one by Apple. It’s free and it’s a good reading.

提交回复
热议问题