20

I need to find the text in an NSTextView, and save it to a file. I can do the saving fine. I have used -stringValue, and -textStorage so far, but neither have worked. 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).

How can I put the text from an NSTextView into an NSString?

Justin
  • 2,122
  • 3
  • 27
  • 47

4 Answers4

38

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.

Nick Weaver
  • 47,228
  • 12
  • 98
  • 108
  • Nothing is happening. I just get an "invisible paragraph". EDIT: I made it do an `NSLog`, and it showed me the right string. The file I saved doesn't show anything but that "large invisible paragraph" that I talked about. What now? – Justin Apr 03 '11 at 21:25
3

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!

Johann Dirdal
  • 1,100
  • 6
  • 12
  • I have tried that. I'm starting to think that I made an error somewhere else, but I can't think of anything that could cause this. EDIT: I just did a quick scan and I found the problem. I am saving a lot of different things, and I forgot a "%@" in my `-stringWithFormat` section. – Justin Apr 03 '11 at 23:19
1

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.

Sangram Shivankar
  • 3,535
  • 3
  • 26
  • 38
Henry Sou
  • 882
  • 2
  • 12
  • 19
0

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.

Justin
  • 2,122
  • 3
  • 27
  • 47