我最初问了一个关于在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点崩溃。
我该如何防止这种情况?
答案 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