开发者

Can I use the same variable in two methods?

I hope this question is not too basic for someone to help me ou开发者_运维百科t on.

I have a variable who's value I define in one method that I would like to use and manipulate in another. Is this possible?

I hope the simple expample code attached will help.

I want the value for 'c' to be 3, but it is only 2.

int a = 0;

-(void)method1  {
int a = 1;
NSLog(@"method 1--> a = %d", a);
}


-(void)method2  {
int b = 2;
NSLog(@"method 2--> b = %d", b);
int c = a + b;
NSLog(@"method 2--> c = %d", c);    
}


int a = 1 in method1 declares new local variable distinct from 'a' declared globally. If you want global 'a' to be used here - omit 'int' here.This will turn declaration of local variable 'a' with initialization into assignment to the globally declared 'a'.


Okay, how it will work for you.

You have redeclared global variable inside your local function. This is not problem, but you should know, that global value will not be used, and after finishing function, global value will become the same.

So, if you want to manipulate variable in both methods, it should be global, for both of them. Like this:

int a = 0;

-(void)method1  {
// int a = 1; Now it is local and will not be changed, after function finishing.
a = 1; // Now it is local, so will stay 1 after the end of method.
NSLog(@"method 1--> a = %d", a);
}


-(void)method2  {
int b = 2;
NSLog(@"method 2--> b = %d", b);
int c = a + b;
NSLog(@"method 2--> c = %d", c);    
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜