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 Programming, there is a section called Using Class Variables where he writes:
You can create class variables for use with your classes, but there’s a hitch: every object of that class shares the same variable, so if one object changes a class variable, that variable is changed for all objects. You create class variables with the static keyword. Class variables are often useful: for example, you can use a class variable to keep track of the number of objects of a particular class created in a program. You’ll do that in this task.
And says to enter the following code:
#import <stdio.h> #import <Foundation/NSObject.h> @interface TheClass: NSObject static int count; //error: cannot declare variable inside @interface or @protocol +(int) getCount; @end ...
This code gives me an error in Xcode 4:
Cannot declare variable inside @interface or @protocol
Is the book wrong or am I doing something wrong?
"In both C and Objective-C, a static variable is a variable that is allocated for the entire lifetime of a program. This is in contrast to automatic variables, whose lifetime exists during a single function call; and dynamically-allocated variables like objects, which can be released from memory when no longer used.
if you want to create static property means, you are creating a class variable. properties are only used for instance variable. If you creating a static means all objects share the same variable; Because it is class variable. you can declare it in the implementation file of your class.
Keyword extern is used for declaring extern variables in Objective-C. This modifier is used with all data types like int, float, double, array, pointer, function etc. Basically extern keyword extends the visibility of the C variables and C functions. Probably that's is the reason why it was named as extern.
You declare the static variable in the implementation file (.m
file). This should work:
// TheClass.h @interface TheClass : NSObject + (int)count; @end // TheClass.m static int theCount = 0; @implementation TheClass + (int) count { return theCount; } @end
It's not a class variable per se; Objective-C has no notion of a class variable. However, coupled with the class method for retrieving this variable, it functions similarly to a class variable. However, it's really just a C static variable that's accessible by the class's implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With