在UIAlertView响应中设置NSString的值,不能在别处使用?

时间:2011-01-30 20:01:32

标签: iphone objective-c cocoa-touch uialertview

我最初问了一个关于在UIAlertView中获取字符串值的问题here,但现在我需要把它拿出来。所以我把这作为一个新问题来整理所有内容,使其更清洁,更清晰。

所以这是我的代码:

在.h文件中..

@property (nonatomic, retain) 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点崩溃。

我该如何防止这种情况?

1 个答案:

答案 0 :(得分:4)

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

我在这里看到的另一件事是,myTestString方法中-somethingElse未定义,因为您只在buttonIndex == 0时为属性分配值。您可能希望在myTestString方法或-init方法中插入alertView:clickedButtonAtIndex:的默认值。

总结一下,我希望你的班级看起来像这样:

  

<强> 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