STANLEY
STANLEY

Reputation: 181

pass a global variable from appdelegate returning null

I set a global variable stores a string value getting from server by socket. and the socket is impletement in appdelegate as below:

in appdelegate.h:

@interface AppDelegate : NSObject <NSStreamDelegate,UIApplicationDelegate> {
    UIWindow *window;
    UITabBarController *tabBarController;
    NSInputStream   *inputStream;
    NSOutputStream  *outputStream;
    NSString *sn,*sn1;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;
@property (nonatomic, retain) NSInputStream *inputStream;
@property (nonatomic, retain) NSOutputStream *outputStream;
@property (nonatomic, retain) NSString *sn,*sn1;

in appdelegate.m

@synthesize  sn,sn1

then when incoming socket stream delegate, I set

sn=input
 NSLog(@"1st sn: %@",sn);//this sn correct! 

and then in SecondViewControll.m I set sn1=@"hello";

in FirstViewControll, I impletement as below: AppDelegate *appDel;

- (void)viewDidLoad
{
    [super viewDidLoad];
      appDel = (AppDelegate *)[[UIApplication sharedApplication] delegate];
   NSLog(@"sn1: %@",sn1);;//this sn correct!

LTField.text=appDel.sn; //this one gives error as below, 

}

Error is:

-[__NSCFSet _isNaturallyRTL]: unrecognized selector sent to instance 0x5f87580
2013-06-23 22:49:26.038 test[2987:12c03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFSet _isNaturallyRTL]: unrecognized selector sent to instance 0x5f87580'

I dont know why the last line gives error but previous line get correct value? I guesss it is because the sn is set value inside the delegate, then it doesnt pass out of the deletegate. How to pass the correct data to this text field from that stream delegate?

Upvotes: 0

Views: 662

Answers (1)

wquist
wquist

Reputation: 2607

Try adding an NSLog(@"sn: %@", sn); after your log of sn1. It's likely that, after you set sn = input;, when that method is complete, input goes out of scope. This make sn an invalid pointer, and you pass LTField.text a null reference. Usually, when you want to keep an NSString object passed as an argument, you would use:

sn = [input copy];

You want to copy the input variable since NSString is immutable, similar to how you would retain a mutable object.

Also, you should change your @property declarations to (nonatomic, copy) for the NSString's, and then you could use

self.sn = input;

if you prefer (since using self and dot notation calls the setter instead of directly using the variable). See this question for some extra information: NSString property: copy or retain?

Upvotes: 1

Related Questions