简体   繁体   中英

Setting the value of an NSString inside a UIAlertView response, can't be used elsewhere?

I originally asked a question here about getting a string value into a UIAlertView but now I need to get it out. So i've put this as a new question to tidy everything up and make it cleaner and clearer.

So here's the code I have:

In the .h file..

@property (nonatomic, retain) NSString *myTestString;

Then in the .m file it's synthesized with:

@synthesize myTestString

Then in the .m file...

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

    if (buttonIndex == 0) {
    self.myTestString = @"test";
    }
}

-(void)somethingElse {

    NSLog(@"%@", myTestString);
}

Then i'd release it in dealloc.

This code would cause a crash at the point of the NSLog.

How can i prevent this?

I'm not sure about your use of @synchronize here. Properties are usually synthesized in the .m file, using @synthesize propertyName; . @synchronize is used for thread safety in a multi-threaded application.

The other thing I can see here is that myTestString can be undefined in your -somethingElse method because you only assign a value to the property when buttonIndex == 0 . You may want to insert a default value for myTestString , either in your -init method, or in the alertView:clickedButtonAtIndex: method.

To summarize, I would expect your class to look something like this:

MyClass.h

@interface MyClass {
    NSString *myTestString;
}
@property (nonatomic, retain) NSString *myTestString;
@end

MyClass.m

@implementation MyClass

@synthesize myTestString;

-(id)init {
    if ((self = [super init]) == nil) { return nil; }
    myTestString = @"";
    return self;
}

-(void)dealloc {
    [myTestString release];
    [super dealloc];
}

-(void)alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        self.myTestString = @"test";
    }
}

-(void)somethingElse {
    NSLog(@"%@", myTestString);
}

@end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM