iphone - 在 UIAlertView 响应中设置 NSString 的值,不能在其他地方使用吗?

标签 iphone objective-c cocoa-touch uialertview

我最初问了一个问题here关于将字符串值放入 UIAlertView 但现在我需要将其取出。所以我把这个作为一个新问题来整理一切并使其更干净、更清晰。

这是我的代码:

在.h文件中..

@property(非原子,保留)NSString *myTestString;

然后在 .m 文件中将其合成为:

@synthesize myTestString

然后在.m文件中...

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

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

-(void)somethingElse {

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

然后我会在 dealloc 中释放它。

此代码会导致 NSLog 处崩溃。

如何防止这种情况发生?

最佳答案

我不确定您对 @synchronize 的使用情况这里。属性通常在 .m 文件中综合,使用 @synthesize propertyName;@synchronize用于多线程应用程序中的线程安全。

我在这里可以看到的另一件事是 myTestString可以在您的 -somethingElse 中未定义方法,因为您仅在 buttonIndex == 0 时才为属性赋值。您可能需要为 myTestString 插入默认值,或者在您的 -init 中方法,或在 alertView:clickedButtonAtIndex:方法。

总而言之,我希望您的类(class)看起来像这样:

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

关于iphone - 在 UIAlertView 响应中设置 NSString 的值,不能在其他地方使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4845149/

相关文章:

iphone - 为 iPhone 构建开源库 (liblo)

objective-c - 防止 UIScrollView 在发生触摸时停止滚动

iphone - 如何使用像indexOfObject这样的东西获取NSArray的索引?

ios - 我可以减少重复声明中的代码吗?

iphone - 如何改变UIWebView滚动的背景?

iphone - UITextField float

ios - UICollectionView 单元格在滚动 UICollectionView 时会抖动

Objective-c:引用ivar persistent?好主意?

ios - 如何在 Swift 中访问 iOS 私有(private) API?

objective-c - iOS:UITableViewCell 中的 UIButton 和 UILabel