PDA

View Full Version : Appending text to NSTextView




Aranince
Dec 16, 2008, 08:15 PM
I'm trying to learn ObjC/Cocoa...but it's working against me.

I created this class:

#import <Cocoa/Cocoa.h>

@interface TestObject : NSObject {
IBOutlet id textInput;
IBOutlet id textOutput;
}
- (IBAction)sender:(id)sender;
@end

The textInput is connected to a NSTextField, the textOutput is connected to a NSTextView, and sender is connected to a button. Here is the sender code:

#import "TestObject.h"

@implementation TestObject

- (IBAction)sender:(id)sender {
NSString *text = [textInput stringValue];
[textOutput setStringValue: text];
}
@end


I want it to append string to the text view, but it's not working. I also tried this and failed.


NSTextStorage *storage = [textInput textStorage];
[storage beginEditing];
[storage appendAttributedString:text];
[storage endEditing];



kainjow
Dec 17, 2008, 04:39 PM
appendAttributedString: takes an NSAttributedString. It appears you're passing it an NSString.

Aranince
Dec 17, 2008, 05:41 PM
Thanks for the reply, but it doesn't work:


- (IBAction)sender:(id)sender {
NSString *text = [textInput stringValue];

NSAttributedString *string = [[NSAttributedString alloc] initWithString:text];
NSTextStorage *storage = [textOutput textStorage];

[storage beginEditing];
[storage appendAttributedString:string];
[storage endEditing];

}

kainjow
Dec 17, 2008, 06:18 PM
Works for me. Are you sure your textOutput and textInput are connected properly in IB? I'd suggest changing their definitions to:
IBOutlet NSTextField *textInput;
IBOutlet NSTextView *textOutput;
This will force IB to only allow connecting those outlets to objects of their types, whereas with "id" IB doesn't know what kind of objects they are, so it'll let you connect them to anything. You most likely have textOutput connected to the text view's scroll view instead of the text view itself. You can also check this by putting a NSLog(@"%@", textOutput); statement in your sender: method.

Aranince
Dec 17, 2008, 06:46 PM
Ok, thanks I got it working. What I did was right click on the object in IB and connected it to the textview that way instead of connecting it from the TextView to the Object. It wasn't connecting for some reason.

johnjay1776
Dec 19, 2008, 11:44 AM
Don't feel too bad ... It appears we're about at the same place as far as learning the language and I made the same mistake on a similar "project".