How to find the text in an NSTextView?

…衆ロ難τιáo~ 提交于 2019-12-03 05:50:16

Try

NSString *text = [[myTextView textStorage] string];

The NSTextStorage inherits from NSMutableAttributedString which inherits from NSAttributedString. The latter implements the string method.

This isn't too obvious if you just look at the NSTextView's instance methods in the documentation.

Try this:

[myTextView string];

If you are struggling to write the textView stringValue into a file try something like this:

    [[myTextView string] writeToFile:@"someFile" atomically:YES encoding:NSUnicodeStringEncoding error:&error];

Hope this helps!

Henry Sou

when setting value, use text.string = @"XXXX";
when getting value, use STRING = [text.string copy];

because if you forget copy, the mutableString will be deliver to STRING. This will raise bugs when you editing multiple things with a single textview.

In order to compile all of the information for anyone else with this question, I am answering my own question. If I am not allowed to do this, please tell me.

The code is actually extremely simple.

Files.h

#import <Cocoa/Cocoa.h>

@interface Files : NSObject {
    IBOutlet id dataToSave;
}

- (IBAction) saveData: (id) sender;

Files.m

@implementation Files

- (IBAction) saveData: (id) sender; {
    NSString *text = [[dataToSave  textStorage] string];
    NSLog(@"%@", text);
    [text writeToFile:@"Users/justin/Desktop/test.txt atomically:YES encoding:NSUTF8StringEncoding error:NULL];
}

Instead of voting this up, vote for the other two people that answered this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!