目标C静态类变量 [英] Objective C static class variables
问题描述
我是Objective C的新手,正在阅读Peachpit Press的Steven Holzner写的一本书,名为"Visual Quickstart Guide:Objective-C"
I am new to Objective C and am reading a book called "Visual Quickstart Guide: Objective-C" by Steven Holzner, Peachpit Press
在第6章:面向对象的编程中,有一个名为使用类变量"的部分,他在其中编写:
In Chapter 6: Object Oriented Programming, there is a section called Using Class Variables where he writes:
您可以创建用于以下用途的类变量 您的课程,但有一个障碍:每个对象 该类的共享相同的变量,因此 如果一个对象改变了一个类变量,那 变量对所有对象都更改.您创建 使用static关键字的类变量. 类变量通常很有用:例如, 您可以使用类变量来跟踪 创建的特定类的对象数 在一个程序中.您将在此任务中完成该操作.
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.
并输入以下代码:
#import <stdio.h>
#import <Foundation/NSObject.h>
@interface TheClass: NSObject
static int count; //error: cannot declare variable inside @interface or @protocol
+(int) getCount;
@end
...
此代码在Xcode 4中给我一个错误:
This code gives me an error in Xcode 4:
无法在@interface或@protocol内声明变量
Cannot declare variable inside @interface or @protocol
这本书是错了还是我做错了什么?
Is the book wrong or am I doing something wrong?
推荐答案
您在实现文件(.m
文件)中声明静态变量.这应该起作用:
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
它本身不是类变量; Objective-C没有类变量的概念.但是,再加上用于检索此变量的类方法,其功能类似于类变量.但是,实际上,它只是一个C静态变量,可由类的实现访问.
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.
这篇关于目标C静态类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!