问题描述:

I want to use Static Var to save a NSString.

So I define a Static Var in a .h file like this:

#ifndef GlobalParameters_h

#define GlobalParameters_h

//access token

static NSString *applicationToken;

#endif

In class A, I change the static var like this:

#import "ClassA.h"

#import "GlobalParameters.h"

extern NSString *applicationToken;

@implementation ClassA

+ (void)parseResponse:(NSString *)response

{

NSDictionary *responseDic = [response objectFromJSONString];

NSString *token = [responseDic objectForKey:@"token"];

applicationToken = [token copy];

NSLog(@"%@",applicationToken);

}

When the debugger run to

applicationToken = [token copy];

I found the "applicationToken" is nil,but the next sentence

NSLog(@"%@",applicationToken);

can output the right value in console! And in ClassB , the "applicationToken" is nil too.

I don't know why the static var is nil. I think the compiler will find the definition of "applicationToken" in GlobalParameters.h.But why I can't modify the static value?

Thanks for your help:)

网友答案:

static global variable mean that it's own for every object-file it's used. So there is willbe own applicationToken for ClassA, ClassB.

To create global variable for all object-files you need this:

In GlobalParameters.h:

#ifndef GlobalParameters_h
#define GlobalParameters_h

//access token
extern NSString *applicationToken;

#endif

In GlobalRarameters.m:

#import "GlobalParameters.h"

NSString *applicationToken;

P.S. I hope you use ARC, because if not, then applicationToken = [token copy]; will cause memory leaks.

网友答案:
  • Hey Its working fine , I am checking like this

    Once check the are you getting "responseDic" (or) not , Check the The dictionary have token key

   static NSString *applicationToken;
   applicationToken = @"srinivas";
   NSLog(@"%@",applicationToken);

   NSDictionary *responseDic = [NSDictionary dictionaryWithObject:@"static" forKey:@"token"];

   NSString *token = [responseDic objectForKey:@"token"];

   applicationToken = [token copy];

   NSLog(@"%@",applicationToken);
       [AppDelegate parseResponse:responseDic];
相关阅读:
Top