Ios 在目标c中只追加一次字符串

Ios 在目标c中只追加一次字符串,ios,iphone,objective-c,Ios,Iphone,Objective C,我只想在视图出现时附加一次字符串。问题是,当我从上一个视图返回时,文本会被反复追加。因为我在视图中保留了附加代码的字符串将出现 这是密码 if (!sharedController.perimeterFencesFreeOfHazard) { NSString *origText = _messageLabel.text; count++; _messageLabel.text = [origText stringByAppendingString:@"\n • Peri

我只想在视图出现时附加一次字符串。问题是,当我从上一个视图返回时,文本会被反复追加。因为我在
视图中保留了附加代码的字符串将出现

这是密码

if (!sharedController.perimeterFencesFreeOfHazard) {
    NSString *origText = _messageLabel.text;
    count++;
    _messageLabel.text = [origText stringByAppendingString:@"\n • Perimeter fences & signs"];
    //count++;
}
如何确保字符串只追加一次?

因此您需要一个标志,它告诉您是否为该视图添加了文本

MyViewController.h:

@interface MyViewController : UIViewController {
    BOOL _textAdded;
}

@end
MyViewController.m:

@implementation MyViewController

- (void)viewWillAppear {
    if (!sharedController.perimeterFencesFreeOfHazard && !_textAdded) {
        NSString *origText = _messageLabel.text;
        count++;
        _messageLabel.text = [origText stringByAppendingString:@"\n • Perimeter fences & signs"];
        _textAdded = YES;
    }
    ...
}

@end

事实上,看起来您正在使用
count
实例变量沿着这条路走下去,这同样好。

将代码从
视图移动将显示:
视图加载:
。正如
viewdiload:
方法在创建视图时只被调用一次。

viewwillbeen将在每次通过其到达前台的方式被调用。将其放入ViewDidLoad…如果每次视图出现时您的条件为真,请将其移至ViewDidLoad并在添加文本后更改sharedController.perimeterFencesFreeOfHazard值。最好的方法是在
ViewDidLoad:
方法中编写代码。还有很多选择。1.您可以比较
BOOL
值。2.
if([str rangeOfString:@“周界围栏和标志”].location==NSNotFound){//append string}否则{//append string}
已经append}UIView
应该是
UIViewController