我正在学习 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 文件不相关,但我认为它会包含它。