开发者

Objective-c variable initialization problem

开发者 https://www.devze.com 2022-12-10 23:18 出处:网络
I have a header file variable.h where i declare all my gl开发者_运维百科obal variable.Then i add this header file my wordgame.m .Here i have

I have a header file variable.h where i declare all my gl开发者_运维百科obal variable.Then i add this header file my wordgame.m .Here i have several function .The problem is that when i initialize some global (int) variable in a function other function do no get the initialized value.Other function always displayed value(=100) for these variable.Even if i do not initialize them they always display value 100.Can any one tell me what is the problem??? As far as i know in objective-c uninitialized variable default value is 0.So why my global variable display value 100.


If you have all your globals in one file, variable.h, such as

int global1, global2;
char shortStr[32];

And #include or #import this into each of your files, then you are creating unique globals in each of these files, independent of and unrelated to each other.

So, if you change the value of global1 in one file, wordgame.m, it would only be that global1 that has been changed, not the global1 in another .m file.

A better way to do this would be to have, in your variable.h:

extern int global1, global2;
extern char shortStr[32];

and in the most relevant .m file, you have:

int global1;

and in another .m file, you'll have:

int global2;
char shortStr[32];

Now, any file that has the variable.h included, will be able to access these globals, and there will be just one instance of these globals, so any value in these globals will be the same across all files.

Better way to do this would be not use globals at all, and use classes, singletons, and delegates...

0

精彩评论

暂无评论...
验证码 换一张
取 消