Документ «Без названия» не может быть сохранен как «Без названия»

Я пытаюсь разработать приложение для Mac на основе документов, используя это пошаговое руководство Apple, и у меня возникли проблемы с сохранением файла (последний шаг). Ошибка, которую я получаю после попытки сохранить файл: документ «Без названия» не может быть сохранен как «— новое имя файла, которое я пытаюсь использовать —»

Я гуглил и не нашел никаких результатов для этой ошибки. Я перепроверил код, и все кажется довольно надежным для учебника. Я задавался вопросом, есть ли у кого-нибудь интуиция относительно того, что здесь может пойти не так.

Код моего основного класса:

#import "MyDocument.h"

@implementation MyDocument

- (id)init
{
    self = [super init];
    if (self) {
        if (mString == nil) {
            mString = [[NSAttributedString alloc] initWithString:@""];
        }
    }
    return self;
}

- (NSAttributedString *) string { return [[mString retain] autorelease]; }

- (void) setString: (NSAttributedString *) newValue {
    if (mString != newValue) {
        if (mString) [mString release];
        mString = [newValue copy];
    }
}

- (void) textDidChange: (NSNotification *)notification {
    [self setString: [textView textStorage]];
}



- (NSString *)windowNibName
{
    // Override returning the nib file name of the document
    // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this method and override -makeWindowControllers instead.
    return @"MyDocument";
}

- (void)windowControllerDidLoadNib:(NSWindowController *) aController
{
    [super windowControllerDidLoadNib:aController];

    if ([self string] != nil) {
        [[textView textStorage] setAttributedString: [self string]];
    }
}

- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
{
    BOOL readSuccess = NO;
    NSAttributedString *fileContents = [[NSAttributedString alloc]
                                        initWithData:data options:NULL documentAttributes:NULL
                                        error:outError];
    if (fileContents) {
        readSuccess = YES;
        [self setString:fileContents];
        [fileContents release];
    }
    return readSuccess;
}

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
    NSData *data;
    [self setString:[textView textStorage]];
    NSMutableDictionary *dict = [NSDictionary dictionaryWithObject:NSRTFTextDocumentType
                                                            forKey:NSDocumentTypeDocumentAttribute];
    [textView breakUndoCoalescing];
    data = [[self string] dataFromRange:NSMakeRange(0, [[self string] length])
                     documentAttributes:dict error:outError];
    return data;
}

Заголовочный файл:

#import <Cocoa/Cocoa.h>

@interface MyDocument : NSDocument
{
    IBOutlet NSTextView *textView;
    NSAttributedString *mString;
}

- (NSAttributedString *)string;
- (void) setString: (NSAttributedString *)value;

@end

person umop    schedule 24.01.2011    source источник


Ответы (2)


В вашем методе -dataOfType:error:, когда вы присваиваете что-то data, вы уверены, что это не ноль? Возврат nil вызовет эту ошибку.

person Joshua Nozzi    schedule 24.01.2011
comment
Ага. Из gdb: print (unsigned int) [data length] возвращает $1 = 271 - person umop; 28.01.2011

Я перестроил проект с нуля, за одним исключением: я не выполнил шаг перетаскивания класса MyDocument во Владельца файла. Учебник был написан для предыдущей версии XCode, хотя там написано, что он для 3.2 (или, может быть, так много произошло в той версии и сейчас), но этот шаг не нужен.

person umop    schedule 05.02.2011