views:

67

answers:

1

Hello, I defined a global variable that is called from other view and it is working first time but not following ones, it keeps with value from first call! Suppose that is a cocoa fundamental problem and variable is not properly defined according its need. Thanks for any idea to solve it.

declaration:

@interface TableArchiveAppDelegate : NSObject <UIAppDelegate> {

    NSString        *varName;
}

@property (nonatomic, copy) NSString *varName;

then related lines on .m file:

@synthesize varName;

-(void)test{

        varName = textField.text;
}

and request from another view:

- (void)viewDidLoad {


    TableArchiveAppDelegate *mainDelegate = (TableArchiveAppDelegate *)[[UIApplication sharedApplication] delegate];

    name.text = mainDelegate.varName;

    [super viewDidLoad];
}
+1  A: 

Not sure I understand the question but the code presented will cause the varName attribute to hold whatever value was set from textField.text when the -test method was called. If you never assign a different value to it, it keeps that initial value forever.

Your problem might be that you're not using the synthesized accessors.

This:

@property (nonatomic, copy) NSString *varName;

...creates a synthesized accessor that copies the NSString object passed to it by creating another NSString instance and populating it with the value of the pass NSString. However, this:

varName = textField.text;

... assigns varName to the address of the string held in textField.Text. Nothing gets copied. If the textField.text changes so does varName because the two iVars share the same string value at the same address. Further, when textField.text releases the string, it will disappear from varName as well.

To copy the string of textField.text you need to use:

self.varName = textField.text;

... to evoke the synthesized access method which has the copy function inside it.

In general you should always use the self. notation when referring to a class' own properties to ensure that they get properly retained/copied/released etc. The only exception, of course, is if you write your own custom accessor.

TechZen
Hi TechZen, self.varName was the solution! I am really thankful for your support and clear steps!!
Ruthy