【问题标题】:how to append string in global variable of string in objective c如何在目标c中的字符串的全局变量中附加字符串
【发布时间】:2018-05-01 11:27:01
【问题描述】:

我在应用程序委托类中创建了全局字符串,并在我的应用程序控件移动时将字符串附加到多个类中,但我只得到最后一个附加的字符串。

@property (nonatomic , strong) NSString *strConacatResponse;

在 appdelegate.m 中

self.strConacatResponse = [self.strConacatResponse stringByAppendingString:[NSString stringWithFormat:@"Name : %@ ",name]];

然后在另一个班级

NSString *strDates = [NSString stringWithFormat:@"\n Common utilities not expire *** EndDate: %@ *** StartDate: %@ ",paramEndDate,paramStartDate];


    [AppDelegate sharedAppDelegate].strConacatResponse =  [[AppDelegate sharedAppDelegate].strConacatResponse stringByAppendingString:strDates];

在我的第三节课

 NSString *strTemp = @" \n Database getSuscriptionStatus error in api calling of apple   ";
    [AppDelegate sharedAppDelegate].strConacatResponse = [[AppDelegate sharedAppDelegate].strConacatResponse stringByAppendingString:strTemp];

但只得到最后一个字符串

【问题讨论】:

  • 你能展示sharedAppDelegate方法吗?
  • 最后一个字符串是什么意思?请问你得到的确切字符串是什么?

标签: objective-c nsstring


【解决方案1】:

您需要先在 appDelegate 中初始化 self.strConacatResponse 并在声明变量时使用 NSMutableString。

第一步是(IN appDelegate):-

self.strConacatResponse=[NSString stringWithFormat:@"Name : %@ ",name];

然后像往常一样追加字符串

【讨论】:

    【解决方案2】:

    将属性变量声明为 NSMutableString

    @property (nonatomic , strong) NSMutableString *strConacatResponse;
    

    在 appdelegate.m 中

    self.strConacatResponse=[[NSMutableString alloc]init];
    self.strConacatResponse = [NSString stringWithFormat:@"Name : %@ ",name];
    

    然后在第二节课

    NSString *strDates = [NSString stringWithFormat:@"\n Common utilities not expire *** EndDate: %@ *** StartDate: %@ ",paramEndDate,paramStartDate];
    
     [AppDelegate sharedAppDelegate].strConacatResponse = [NSString stringWithFormat:@"%@ %@ ",[AppDelegate sharedAppDelegate].strConacatResponse,strDates ];
    

    三等舱

    NSString *strTemp = @" \n Database getSuscriptionStatus error in api calling of apple   ";
    
    
    [AppDelegate sharedAppDelegate].strConacatResponse = [NSString stringWithFormat:@"%@ %@ ",[AppDelegate sharedAppDelegate].strConacatResponse,strTemp];
    

    【讨论】:

      【解决方案3】:

      您的字符串需要是可变的才能附加新字符串:

      @property (nonatomic , strong) NSMutableString *strConacatResponse;
      

      然后(例如)在AppDelegate

      strConacatResponse = [NSMutableString new];
      

      现在你可以给它添加更多的字符串了。

      【讨论】:

        【解决方案4】:

        只想指出现有的日志记录 API,因为您似乎正在尝试实现某种日志记录:os_log、NSLog、CocoaLumberjack。 这些是久经考验的 API,因此根据您的需要,不重新发明轮子可能是更好的选择。

        【讨论】:

          猜你喜欢
          • 2020-03-06
          • 1970-01-01
          • 1970-01-01
          • 2014-02-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-09
          • 1970-01-01
          相关资源
          最近更新 更多