开发者

Global variable call working only first time

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 {


    TableArchiveAppDel开发者_如何学JAVAegate *mainDelegate = (TableArchiveAppDelegate *)[[UIApplication sharedApplication] delegate];

    name.text = mainDelegate.varName;

    [super viewDidLoad];
}


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜