简体   繁体   English

如何在NSTextView中查找文本?

[英]How to find the text in an NSTextView?

I need to find the text in an NSTextView , and save it to a file. 我需要在NSTextView找到文本,并将其保存到文件中。 I can do the saving fine. 我可以保存罚款。 I have used -stringValue , and -textStorage so far, but neither have worked. 到目前为止,我使用了-stringValue-textStorage ,但两者都没有用。 When I put -stringValue in, it just gave me (null), and when I put -textStorage in, it gave me a very large chunk of nothing (like a long paragraph of invisible text). 当我把-stringValue放进-stringValue的时候,它只给了我(null),当我把-textStorage放进-textStorage的时候,它给了我很大一部分(就像一段长长的隐形文本)。

How can I put the text from an NSTextView into an NSString ? 如何将NSTextView的文本放入NSString

Try 尝试

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

The NSTextStorage inherits from NSMutableAttributedString which inherits from NSAttributedString . NSTextStorage继承自NSMutableAttributedString ,后者继承自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. 如果您只是查看文档中的NSTextView实例方法,这不是太明显。

Try this: 试试这个:

[myTextView string];

If you are struggling to write the textView stringValue into a file try something like this: 如果您正在努力将textView stringValue写入文件,请尝试以下方法:

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

Hope this helps! 希望这可以帮助!

when setting value, use text.string = @"XXXX"; 设置值时,使用text.string = @"XXXX";
when getting value, use STRING = [text.string copy]; 获取值时,使用STRING = [text.string copy];

because if you forget copy, the mutableString will be deliver to STRING . 因为如果忘记了复制, mutableString将被传递给STRING This will raise bugs when you editing multiple things with a single textview . 当您使用单个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 Files.h

#import <Cocoa/Cocoa.h>

@interface Files : NSObject {
    IBOutlet id dataToSave;
}

- (IBAction) saveData: (id) sender;

Files.m 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. 而不是投票,投票给另外两个回答这个问题的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM