开发者

Why aren't my variables persisting between methods? - iPhone

开发者 https://www.devze.com 2023-03-10 19:26 出处:网络
Header file: NSString *righta; @property(nonatomic, retain) NSString *righta; (I don\'t usually make @property declarations for my variables but thought this might help the variable persist through

Header file:

NSString *righta;
@property(nonatomic, retain) NSString *righta;

(I don't usually make @property declarations for my variables but thought this might help the variable persist through the class, though it hasn't)

Implementation file:

@synthesize righta;

- (void) function1 {
     righta = [NSString stringWithFormat:@"A"];
}

- (IBAction)function2:(id)sender {
     NSLog(@"righta is still %@", righta);
}

On trying to access the val开发者_高级运维ue of the string in the second function, I receive an "EXC_BAD_ACCESS" and the app crashes.

Any help would be GREATLY appreciated.

Thanks!


stringWithFormat returns an autoreleased object. You must retain it. Note that you are accessing the ivar directy, not the property so the string is not getting retained. Use the property instead:

self.righta = [NSString stringWithFormat:@"A"];

Some programmers prefer to synthesize their properties with a different ivar name to avoid accessing the ivar directly by mistake.

@synthesize righta = righta_;


You must use

self.righta  = [NSString stringWithFormat:@"A"];

To assign the variable otherwise the accessor is not used and the value is not retained.


Change function1 to:

self.righta = [NSString stringWithFormat:@"A"];

You were assigning directly to the righta ivar without retaining the string.

0

精彩评论

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