在同一类的不同方法中使用NSString对象的属性时出错?

时间:2013-07-29 14:18:58

标签: ios objective-c nsstring

我创建了一个NSString属性,并在类的函数中初始化它 现在我使用NSLog()另一个函数来显示这个字符串包含的内容。

而不是得到我输入的内容,我得到了奇怪的字符串 我的代码清单如下:

@property(nonatomic, retain) NSString *stringWithProperty;

现在正在实施:

  - (IBAction)FirstButtonPressed:(id)sender
{   

NSString *x= [labelForSecondLine.text substringWithRange:NSMakeRange(0, 2)];
NSString *y= [labelForSecondLine.text substringWithRange:NSMakeRange(3, 2)];
NSString *z= [labelForSecondLine.text substringWithRange:NSMakeRange(5, 2)];

stringWithProperty=[NSString stringWithFormat:@"%@-%@-20%@",x,y,z];

}

- (IBAction)secondButtonPressed:(id)sender
{
NSLog(@"%@",stringWithProperty);
}

当我先按下第二个按钮后,我得到了这个输出:

<UIButtonContent: 0x71533b0 Title = (null), AttributedTitle = (null), Image = (null), Background = (null), TitleColor = UIDeviceWhiteColorSpace 1 1, ShadowColor = UIDeviceWhiteColorSpace 0 0.5>

有谁能告诉我,我或这个代码出了什么问题?

2 个答案:

答案 0 :(得分:0)

如果属性没有@synthesize stringWithProperty=stringWithProperty;,则底层变量名称将设置为_stringWithProperty。你正在点击一些具有相同名称的对象(看起来像是一些按钮内容)。使用self.stringWithProperty访问媒体资源或(如果您确实需要这样做)_stringWithProperty直接访问它的变量(或者更明确地更明确self->_stringWithProperty

答案 1 :(得分:0)

属性很奇怪,直到你习惯了它们。 (事实上​​,即使你习惯了它们,它们也很奇怪。)

让事情变得复杂的是,Apple一直在玩物业的运作方式。

如果您希望相对独立于编译器版本,并避免各种奇怪,请在@synthesize stringWithProperty;语句下方插入@implementation始终将该属性称为{ {1}}。在编译器的更高版本中,这些步骤是不必要的,但它们没有任何损害。