2014-04-27 4 views
0

Моя проблема: все работает отлично, но когда я хочу открыть файл, сохраненный с помощью TahDoodle (программа для изучения из большой книги nerd ranches (Objective-C Programming: The Big Nerd Ranch Guide) ., программа падает я взял взгляд в «утечки» инструмент и видел много утечек Но я не знаю, как это исправитьTahDoodle падает при открытии файлов

Вот мой код:..

BNRDocument.m

#import "BNRDocument.h" 

@implementation BNRDocument 

# pragma mark - NSDocument Overrides 

- (id)init 
{ 
    self = [super init]; 
    if (self) { 
     // Add your subclass-specific initialization here. 
     // If an error occurs here, return nil. 
    } 
    return self; 
} 

- (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 @"BNRDocument"; 
} 

# pragma mark - Actions 

- (IBAction)createNewItem:(id)sender 
{ 
    // Falls es noch kein Array gibt, erstellen Sie einfach 
    // eines, in dem unsere neue Aufgabe gespeichert wird 
    if (!toDoItems) { 
     toDoItems = [[NSMutableArray alloc]init]; 
    } 
    [toDoItems addObject:@"New Item"]; 

    // -reloadDate aktualisiert die Tabellenansicht und fordert von 
    // dataSource (das in diesem Fall zufällig dieses BNRDocument ist) 
    // neue Daten zur Darstellung an 
    [itemTableView reloadData]; 

    // -updateChangeCount: teilt der Anwendung mit, ob im Dokument 
    // ungespeicherte Änderungen vorhanden sind oder nicht. 
    // NSChangeDone kennzeichnet das Dokument als ungespeichert 
    [self updateChangeCount:NSChangeDone]; 
} 

# pragma mark - Data Source Methods 

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tv 
{ 
    // Diese Tabellenansicht soll die todoItems darstellen, 
    // und somit ist die Zahl der Einträge in der Tabellenansicht 
    // gleich der Zahl der Objekte im Array 
    return [toDoItems count]; 
} 

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row 
{ 
    // Gibt das Element aus todoItems zurück, das mit der Zelle 
    // korrespodiert, die die Tabellenansicht darstellen will 
    return [toDoItems objectAtIndex:row]; 
} 

- (void)tableView:(NSTableView *)tableView 
    setObjectValue:(id)object 
    forTableColumn:(NSTableColumn *)tableColumn 
       row:(NSInteger)row 
{ 
    // Ändert der Benutzer ein To-do-Element in der Tabellenansicht 
    // wird das totoItems-Array aktualisiert 
    [toDoItems replaceObjectAtIndex:row withObject:object]; 

    // Dann wird das Dokument gekennzeichnet, es habe 
    // ungespeicherte Änderungen 
    [self updateChangeCount:NSChangeDone]; 
} 

- (void)windowControllerDidLoadNib:(NSWindowController *)aController 
{ 
    [super windowControllerDidLoadNib:aController]; 
    // Add any code here that needs to be executed once the windowController has loaded the document's window. 
} 

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError 
{ 
    // Diese Methode wird beim Speichern unseres Dokuments aufgerufen 
    // Wir sollen dafür sorgen, dass der Aufrufer ein NSData-Objekt bekommt, 
    // das unsere Daten umhüllt um sie auf Festplatte schreiben zu können 

    // Falls es kein Array gibt, schreibn wir fürs Erste ein leeres Array 
    if (!toDoItems) { 
     toDoItems = [[NSMutableArray alloc]init]; 
    } 

    // Packt unser toDoItems-Array in ein NS Data-Objekt 
    NSData *data = [NSPropertyListSerialization dataWithPropertyList:toDoItems 
                   format:NSPropertyListXMLFormat_v1_0 
                  options:0 
                   error:outError]; 

    // Gibt das neu gepackte NSData-Objekt zurück 
    return data; 
} 

- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError 
{ 
    // Diese Methode wird aufgerufen, wenn ein Dokument geladen wird 
    // Wir bekommen ein NSData-Objekt und sollen daraus unsere Daten ziehen 

    // Extrahiert ToDoItems 
    toDoItems = [NSPropertyListSerialization propertyListWithData:data 
                  options:NSPropertyListMutableContainers 
                  format:NULL 
                  error:outError]; 

    // Gibt unabhängig vom obigen Aufruf Erfolg oder Misslingen zurück 
    return (toDoItems !=nil); 
} 
@end 

BNRDocument.h

#import <Cocoa/Cocoa.h> 

@interface BNRDocument : NSDocument <NSTableViewDataSource> 
{ 
    NSMutableArray *toDoItems; 
    IBOutlet NSTableView *itemTableView; 
} 

-(IBAction)createNewItem:(id)sender; 

@end 

я красный Alle части кода в 5 раз, а моя подруга сделала 2 раза. Но все, что написано в книге, находится в моем заявлении, даже исправление с этой должности: http://forums.bignerdranch.com/viewtopic.php?f=160&t=3494

Если вы можете мне помочь, было бы здорово! Спасибо :)

С наилучшими пожеланиями, Christian

редактирования: Хорошо, я просто забыл консоль:

[Switching to process 746 thread 0x0] 
[Switching to process 746 thread 0x3d03] 
[Switching to process 746 thread 0x903] 
2014-04-27 22:03:55.137 TahDoodle[746:903] *** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0) 
2014-04-27 22:03:55.146 TahDoodle[746:903] *** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0) 
2014-04-27 22:04:02.338 TahDoodle[746:903] *** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0) 
2014-04-27 22:04:02.342 TahDoodle[746:903] *** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0) 
2014-04-27 22:04:06.169 TahDoodle[746:903] *** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0) 
2014-04-27 22:04:06.175 TahDoodle[746:903] *** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0) 
2014-04-27 22:04:09.528 TahDoodle[746:903] *** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0) 
2014-04-27 22:04:09.532 TahDoodle[746:903] *** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0) 
kill 
quit 

Но я не знаю, что это значит. Но, похоже, это не ошибка чтения.

edit2: Вот содержание файла, который должен быть загружен:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 
<plist version="1.0"> 
<array> 
    <string>New Item</string> 
    <string>New Item</string> 
</array> 
</plist> 

Edit3

Единственные точки останова здесь:

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row 
{ 
    // Gibt das Element aus todoItems zurück, das mit der Zelle 
    // korrespodiert, die die Tabellenansicht darstellen will 

    return [toDoItems objectAtIndex:row]; 

инструмента, как найти причины исключения очень круто. Спасибо за это. Я установил ручные точки останова на всех «возвратах».

вещь ... предметы загружены. Я вижу их в программе, но когда я нажимаю на окно, программа вылетает с: EXC_BAD_ACCESS.

Когда я дважды щелкните на сохраненном файле, TahDoodle открыт, а затем он падает мгновенно с этим сообщением:

[...] 
Exception Type: EXC_BAD_ACCESS (SIGSEGV) 
Exception Codes: KERN_INVALID_ADDRESS at 0x000000000000001b 
Crashed Thread: 0 Dispatch queue: com.apple.main-thread 

Application Specific Information: 
objc_msgSend() selector name: objectAtIndex: 


Thread 0 Crashed: Dispatch queue: com.apple.main-thread 
0 libobjc.A.dylib     0x00007fff89b1108c objc_msgSend_vtable10 + 12 
1 com.apple.AppKit    0x00007fff8275aa7c -[NSTableView preparedCellAtColumn:row:] + 323 
2 com.apple.AppKit    0x00007fff82773963 -[NSTableView _drawContentsAtRow:column:withCellFrame:] + 47 
3 com.apple.AppKit    0x00007fff827729fc -[NSTableView drawRow:clipRect:] + 1242 
4 com.apple.AppKit    0x00007fff827722ef -[NSTableView drawRowIndexes:clipRect:] + 369 
5 com.apple.AppKit    0x00007fff82770c9c -[NSTableView drawRect:] + 1302 
6 com.apple.AppKit    0x00007fff82766cc5 -[NSView _drawRect:clip:] + 3390 
7 com.apple.AppKit    0x00007fff82765938 -[NSView _recursiveDisplayAllDirtyWithLockFocus:visRect:] + 1325 
8 com.apple.AppKit    0x00007fff82765ca2 -[NSView _recursiveDisplayAllDirtyWithLockFocus:visRect:] + 2199 
9 com.apple.AppKit    0x00007fff82765ca2 -[NSView _recursiveDisplayAllDirtyWithLockFocus:visRect:] + 2199 
10 com.apple.AppKit    0x00007fff82765ca2 -[NSView _recursiveDisplayAllDirtyWithLockFocus:visRect:] + 2199 
11 com.apple.AppKit    0x00007fff82765ca2 -[NSView _recursiveDisplayAllDirtyWithLockFocus:visRect:] + 2199 
12 com.apple.AppKit    0x00007fff8276400a -[NSView _recursiveDisplayRectIfNeededIgnoringOpacity:isVisibleRect:rectIsVisibleRectForView:topView:] + 767 
13 com.apple.AppKit    0x00007fff82763b2c -[NSThemeFrame _recursiveDisplayRectIfNeededIgnoringOpacity:isVisibleRect:rectIsVisibleRectForView:topView:] + 254 
14 com.apple.AppKit    0x00007fff827603de -[NSView _displayRectIgnoringOpacity:isVisibleRect:rectIsVisibleRectForView:] + 2683 
15 com.apple.AppKit    0x00007fff826d9c0e -[NSView displayIfNeeded] + 969 
16 com.apple.AppKit    0x00007fff826d4aba _handleWindowNeedsDisplay + 678 
17 com.apple.Foundation   0x00007fff82449bc5 __NSFireTimer + 114 
18 com.apple.CoreFoundation  0x00007fff832b8bb8 __CFRunLoopRun + 6488 
19 com.apple.CoreFoundation  0x00007fff832b6d8f CFRunLoopRunSpecific + 575 
20 com.apple.HIToolbox    0x00007fff87ac37ee RunCurrentEventLoopInMode + 333 
21 com.apple.HIToolbox    0x00007fff87ac35f3 ReceiveNextEventCommon + 310 
22 com.apple.HIToolbox    0x00007fff87ac34ac BlockUntilNextEventMatchingListInMode + 59 
23 com.apple.AppKit    0x00007fff826a9eb2 _DPSNextEvent + 708 
24 com.apple.AppKit    0x00007fff826a9801 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 155 
25 com.apple.AppKit    0x00007fff8266f68f -[NSApplication run] + 395 
26 com.apple.AppKit    0x00007fff826683b0 NSApplicationMain + 364 
27 BuRo.TahDoodle     0x00000001000015e4 start + 52 

Thread 1: Dispatch queue: com.apple.libdispatch-manager 
0 libSystem.B.dylib    0x00007fff89bdbc0a kevent + 10 
1 libSystem.B.dylib    0x00007fff89bddadd _dispatch_mgr_invoke + 154 
2 libSystem.B.dylib    0x00007fff89bdd7b4 _dispatch_queue_invoke + 185 
3 libSystem.B.dylib    0x00007fff89bdd2de _dispatch_worker_thread2 + 252 
4 libSystem.B.dylib    0x00007fff89bdcc08 _pthread_wqthread + 353 
5 libSystem.B.dylib    0x00007fff89bdcaa5 start_wqthread + 13 

Thread 2: 
0 libSystem.B.dylib    0x00007fff89bdca2a __workq_kernreturn + 10 
1 libSystem.B.dylib    0x00007fff89bdce3c _pthread_wqthread + 917 
2 libSystem.B.dylib    0x00007fff89bdcaa5 start_wqthread + 13 

Thread 3: 
0 libSystem.B.dylib    0x00007fff89bdca2a __workq_kernreturn + 10 
1 libSystem.B.dylib    0x00007fff89bdce3c _pthread_wqthread + 917 
2 libSystem.B.dylib    0x00007fff89bdcaa5 start_wqthread + 13 
[...] 
+0

Забудьте о просачивающемся приборе, просочившиеся объекты не вызывают сбоев, если у вас не закончилось место на жестком диске. Какой результат вы видите на консоли при сбое? –

+0

см. Мои правки «edit» и «edit2». Спасибо за вашу помощь. –

+0

Эта ошибка означает, что в нем нет массива, в котором нет элементов, а какой-то код пытается получить доступ к первому элементу массива (которого не существует). Я не вижу ошибку где-нибудь в коде, который вы опубликовали. Возможно, попробуйте установить точку останова на «Все исключения», чтобы найти строку кода, где она сначала не удается, а затем сообщить нам, что такое трассировка стека. Вот как вы положили точку останова на «Все» исключения: https://developer.apple.com/library/ios/recipes/xcode_help-breakpoint_navigator/articles/add_an_exception_breakpoint.html –

ответ

0

Я изменил мою Xcode версии от 4.2 до 5.1. Теперь он работает отлично. :-)

Смежные вопросы