【问题标题】:Have trouble appending to an NSMutableString附加到 NSMutableString 时遇到问题
【发布时间】:2010-11-28 10:17:13
【问题描述】:
@interface MainView : UIView { 
    NSMutableString *mutableString; 
}
@property (nonatomic, retain) NSMutableString *mutableString;
@end

@implementation MainView
@synthesize mutableString;

-(void) InitFunc {  
    self.mutableString=[[NSMutableString alloc] init];
 }

-(void) AppendFunc:(*NString) alpha { 
    [self.mutableString stringByAppendingString:@"hello"];
    NSLog(@"the appended String is: %@",self.mutableString);
    int len=[self.mutableString length];
}

大家好,

我只想知道我哪里做错了??? .我尝试了这段代码,但“mutableString”没有附加任何值(因为“len”的值是“0”并且 NSLog 没有为“mutableString”打印任何值),虽然我已经在网上搜索了解决方案,但人们在同样的时尚,但我不知道为什么我的代码不起作用。

提前致谢

MGD

【问题讨论】:

    标签: objective-c nsstring nsmutablestring


    【解决方案1】:

    stringByAppendingString: 创建新字符串。请改用appendString::

    [mutableString appendString:@"hello"]

    【讨论】:

      【解决方案2】:

      1) 您的方法名称违反了命名约定:使用小写字母开头。

      2) stringByAppendingString 作为结果返回一个新字符串,并且不会修改您的原始字符串。你应该改用[self.mutableString appendString:@"hello"];。

      3) 您的 init 方法正在泄漏。您应该使用mutableString = [[NSMutableString alloc] init];,而不是使用点语法,否则它将是retained(并且会缺少release)。

      【讨论】:

      • 谢谢兄弟,问题解决了!,其实我是新手,我需要像你这样有经验的人的指导:)
      【解决方案3】:

      天哪,真是一团糟。 stringByAppendingString 不会更改字符串,它会创建并返回一个新字符串:

      // Sets str2 to “hello, world”, does not change str1.
      NSMutableString *str1 = [NSMutableString stringWithString:@"hello, "];
      NSString *str2 = [str1 stringByAppendingString:@"world"];
      

      如果要更改可变字符串本身,请使用appendString 方法:

      // Does not return anything, changes str1 in place.
      [str1 appendString:@"world"];
      

      另外,这是一个泄漏:

      self.mutableString = [[NSMutableString alloc] init];
      

      最好这样写:

      mutableString = [[NSMutableString alloc] init];
      

      ...因为在init 和dealloc is not the best idea 中使用了访问器。

      【讨论】:

      • oooopsss 耶hhhh :$ ...对不起,我发布了这么愚蠢的问题顺便说一句谢谢你的帮助
      • 这不是一个愚蠢的问题,编写乱七八糟的代码也没有错,我们都经历过。 (见鬼,我仍然写乱七八糟的代码。)只是试着一直变得更好一点,仅此而已。
      • 非常感谢...我会保留你宝贵的建议:)
      猜你喜欢
      • 2023-03-12
      • 2015-06-04
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-09
      • 1970-01-01
      相关资源
      最近更新 更多