简体   繁体   中英

NSTextView does not receive string

I am writing a basic text editor and need to implement a reading method. Since I am using NSDocument, I decide to override the method - (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError

Below is my code for the method:

- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
{
    BOOL readSuccess = NO;
    NSString *fileContents = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    if (!fileContents && outError) {
    *outError = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:nil];
    }

    if (fileContents) {
    readSuccess = YES;

    [textView setString: fileContents];
    NSLog(@"%@",[textView string]);
    }
    return YES;
}

The NSLog returns NULL. I have connected the textView object in my xib to the textView property file's owner(which is the NSDocument subclass). What is wrong with my code?

My source files are just the NSDocument subclass interface and implementation files(GNDocument.h and .m). I have two xib files: MainMenu.xib and GNDocument.xib(file owner is set to GNDocument). I am able to NSLog the string to the console. The only problem seems that the NSTextView is not connected to the file's owner even though I have already done the connection(drag from file owner's textView property to the NSTextView).

I hope someone can enlighten me as I really don't see why it doesn't work. PLease point me to the correct direction, or at least some hint. Thanks.

I found the answer. There is nothing wrong with the connections. What happens is that after I read a file using

- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError  

I should then setString: to the textView object in the

- (void)windowControllerDidLoadNib:(NSWindowController *)aController

I will need to hold the string that was read from the file in another NSString ivar so that it can be passed to the windowControllerDidLoadNib method.

What I did wrong previously was that I setString: in the same method that opens and read the file method, which is before the windowController load the nib file. Hence the textView does not exist before that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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