自学XCode/Objective-C:'静态'似乎并不意味着我认为*它意味着什么

Lau*_*elS 3 objective-c

我正在研究Holzner所着的"Visual Quick Start,Objective-C"一书中的例子.我花了很多时间在每个例子上,调试代码是更快的部分,然后逐步告诉自己为什么每行代码都工作,每行中的每个单词做什么,并决定作者使用一种做法的原因事情与另一个.然后我用自己的一些故事重复这个例子.这似乎是从结构化程序员转变为类似oop的好方法.它适用于这些示例,因为他一次只做一个概念.(我已经完成了另外两本书的工作,这个想法对我来说不起作用.一旦我对某些东西感到困惑,我只是感到困惑.在更长,更复杂的例子中有太多的变数.)

在当前示例(第137页)中,Holzner使用"静态"一词.我查看了本书中的示例来确定这个词的含义.我还阅读了Bjarne Stroustrups的C++编程语言书中的描述(我理解C++和Objective-C并不完全相同)

(Bjarne Stroustup p 145)使用静态变量作为内存,而不是"可能被其他函数访问和破坏"的全局变量

这就是我理解的"静态"意味着结果.我认为这意味着静态变量的值永远不会改变.我认为这意味着它就像一个恒定值,一旦你将它设置为1或5,它就无法在运行期间被改变.

但是在这个示例代码中,静态变量的值确实发生了变化.所以我真的不清楚"静态"意味着什么.

(请忽略我留下评论的'后续问题'.我不想改变我的运行中的任何内容,并冒着创建阅读错误的风险

谢谢你能给我的任何线索.我希望我没有在这个问题上加入太多细节.

月桂树

.....

Program loaded.
run
[Switching to process 2769]
Running…
The class count is 1
The class count is 2

Debugger stopped.
Program exited with status value:0.
Run Code Online (Sandbox Code Playgroud)

.....

//
//  main.m
//  Using Constructors with Inheritance
//Quick Start Objective C page 137
//

#include <stdio.h>

#include <Foundation/Foundation.h>

@interface TheClass : NSObject

// FOLLOWUP QUESTION - IN last version of contructors we did ivars like this
//{
//  int number;
//}

// Here no curly braces. I THINK because here we are using 'static' and/or maybe cuz keyword?
//   or because in original we had methods and here we are just using inheirted methods

//  And static is more long-lasting retention 'wise than the other method
//             * * * 

// Reminder on use of 'static' (Bjarne Stroustup p 145)
// use a static variable as a memory, 
//     instead of a global variable that 'might be accessed and corrupted by other functions'

static int count;

// remember that the + is a 'class method' that I can execute 
//         using just the class name, no object required (p 84. Quick Start, Holzner)

// So defining a class method 'getCount'

+(int) getCount;


@end

@implementation TheClass

-(TheClass*) init
{
    self = [super init];
    count++;
    return self;
}

+(int) getCount
{ 
    return count;
}

@end


// but since 'count' is static, how can it change it's value? It doeeessss....


int main (void) {
    TheClass *tc1 =  [TheClass new]  ;
    printf("The class count is %i\n", [TheClass getCount]);

    TheClass *tc2 =  [TheClass new]  ;
    printf("The class count is %i\n", [TheClass getCount]);


    return 0;
}
Run Code Online (Sandbox Code Playgroud)

No *_*lar 10

"static"与C++"const"不同.相反,它是一个声明,变量只被声明一次,并在内存中保持(因此是静态的).假设你有一个功能:

int getIndex()
{
    static int index = 0;
    ++index;
    return index;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,"static"告诉编译器将索引值保留在内存中.每次访问它时都会改变:1,2,3,....

比较这个:

int getIndex()
{
    int index = 0;
    ++index;
    return index;
}
Run Code Online (Sandbox Code Playgroud)

每次创建索引变量时,这将返回相同的值:1,1,1,1,1,....