0

我正在学习 Cocoa/Objective-C,并且我试图能够修改NSString和编辑字符串中的单个字符。我已经设法将其更改为一个字符数组,然后将其更改回来,但是当我尝试这样做时c[0] = 'b',它说“只读变量不可分配”。我已经包含了 .m 文件和 .h 文件。

这是 .m 文件:

import "AppDelegate.h"

@implementation AppDelegate

@synthesize textField, myLabel;

-(IBAction)changeLabel:(id)sender {
    NSString *message = [[NSString alloc] initWithFormat:@"Hello, %@!", [textField stringValue]];
    NSString *message2 = [[NSString alloc] initWithFormat:@"%@ This part was added on afterwards.", message];
    const char *c = [message2 UTF8String];
    c[0] = 'b';
    NSString *output;
    output = [NSString stringWithCString:c encoding:NSASCIIStringEncoding];
    [myLabel setStringValue:output];
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{

}

@end

这是 .h 文件:

@interface AppDelegate : NSObject <NSApplicationDelegate>

@property (assign) IBOutlet NSWindow *window;
@property (weak) IBOutlet NSTextField *textField;
@property (weak) IBOutlet NSTextField *myLabel;

-(IBAction)changeLabel:(id)sender;
@property (weak) IBOutlet NSTextField *changeButtonText;

@end

我假设 .h 文件不相关,但我认为它会包含它。

4

3 回答 3

0

NSString is a container for an immutable string. Taken from official reference:

The NSString class declares the programmatic interface for an object that manages immutable strings. An immutable string is a text string that is defined when it is created and subsequently cannot be changed.

Basically, by using just cocoa, you can generate new NSStrings by replacing characters in existing strings, for example with:

- (NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement

but you can't modify the same object. Exactly for this reason UTF8String returns a const char* which is an immutable pointer to a sequence of character. That's why you get the error.

You can use the provided NSString methods to generate new strings or copy the const char* C string to a char* (through, for example, strdup).

于 2013-05-26T23:16:53.083 回答
0

c is a const char* -> its initialising value is its value throughout the whole runtime. Maybe you should erase the const keyword.

于 2013-05-26T23:17:27.487 回答
0

在 Objective-C 中,NSString实例是不可修改的,对于可修改的字符串,您需要NSMutableString. 或者,您可以从旧字符串创建新字符串。不幸的是NSMutableString/NSString没有 , 的倒数characterAtIndex:,要更改您需要使用stringByReplaceCharactersInRange:withString:/的单个字符,您需要在replaceCharactersInRange:withString:其中提供要更改的字符的范围 - 位置和长度。以下是您重写的部分代码以使用这些代码,首先创建一个字符串:

NSString *message2 = [[NSString alloc] initWithFormat:@"%@ This part was added on afterwards.", message];
NSString *output = [message2 stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:@"b"];

第一个选项创建一个字符串。使用可修改的字符串:

NSMutableString *message2 = [[NSMutableString alloc] initWithFormat:@"%@ This part was added on afterwards.", message];
[message2 replaceCharactersInRange:NSMakeRange(0,1) 

第二个选项更改.引用的字符串message2

您是创建新字符串还是使用可修改字符串取决于您需要进行多少更改以及是否需要保留原始字符串。

于 2013-05-26T23:30:20.743 回答