2014-10-29 72 views
0

我已經實現了一個簡單的應用程序,該應用程序主要輸出有關給定三角形的信息(請參閱圖像)。我已經以編程方式創建了三角形。我想改進這個例子,提供一種機制來打開一個帶有邊的說.tri文件(例如3 4 5)。我怎樣才能做到這一點?我已經做了一些研究,發現有一種叫做openDocument的方法。我如何在我的應用程序中使用它?有人能給我一個如何實現這個目標的例子嗎?顯然這不是一個基於文檔的應用程序..我有github上的這個代碼:https://github.com/mcand/TableViewMacExample使用Objective-C爲OS X應用程序打開文檔

Current Application

+0

我應該搜索什麼?我應該實現自己的函數來打開文件還是使用openDocument函數?我嘗試過在API上搜索,但我不太明白。 – andrefurquin 2014-10-29 16:53:55

+0

當我聲明這個方法時: - (IBAction)openDocument:(id)sender { }我得到打開的菜單,但沒有任何反應。 – andrefurquin 2014-10-29 17:50:26

+0

我設法讓面板看起來像這樣: – andrefurquin 2014-10-29 17:56:11

回答

0

打開文件後,我無法更改我的NSTableView的值。該代碼是這樣的:

- (IBAction)openDocument:(id)sender{ 
    NSOpenPanel* panel = [NSOpenPanel openPanel]; 
    [panel setAllowedFileTypes:[NSArray arrayWithObjects:@"tri", @"qua",nil]]; 

    [panel beginWithCompletionHandler:^(NSInteger result){ 
     if (result == NSFileHandlingPanelOKButton) { 
      NSURL* file = [[panel URLs] objectAtIndex:0]; 

      [self performSelectorInBackground:@selector(triangle:) withObject:file]; 

     } 

    }]; 
} 


-(void) triangle:(NSURL *)file{ 

     NSError *error; 

     NSString *words = [[NSString alloc] initWithContentsOfURL:file encoding:NSUTF8StringEncoding error:&error]; 

     NSLog(@"%@", words); 

     NSArray* lines = [words componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]; 

     NSMutableArray *shapes = [[NSMutableArray alloc] init]; 

     while (lines) { 

      NSArray*info = [words componentsSeparatedByString:@";"]; 

      // Creates triangles to be populated 
      CGFloat side1 = (CGFloat)[info[0] floatValue]; 
      CGFloat side2 = (CGFloat)[info[1] floatValue]; 
      CGFloat side3 = (CGFloat)[info[2] floatValue]; 

      Triangle *triangle = [[Triangle alloc] initWithSides:side1 side:side2 andSide:side3]; 

      [shapes addObject:triangle]; 
     } 

     self.formsArray = shapes; 

     [self performSelectorOnMainThread:@selector(updateTableView) withObject:nil waitUntilDone:YES]; 

} 

-(void)updateTableView{ 
    [self.tableView reloadData]; 
} 

@end 
+0

該項目在我的github上。希望任何人都可以幫助我https://github.com/mcand/TableViewMacExample。 – andrefurquin 2014-10-30 03:26:31

+0

問題是我讀文件的方式。 – andrefurquin 2014-10-31 16:16:51

0

我設法讓面板看起來像下面。

- (IBAction)openDocument:(id)sender{ 
    NSOpenPanel* openPanel = [NSOpenPanel openPanel]; 

    [openPanel setAllowedFileTypes:[NSArray arrayWithObjects:@"tri", @"qua",nil]]; 
    [openPanel runModal]; 

} 
+0

...也可以考慮 '-beginSheetModalForWindow:completionHandler:'如果被打開的東西最終會在特定的現有窗口中結束,而不是被打開爲新的東西。 – Tommy 2014-10-29 18:04:32

+0

謝謝@Tommy。 – andrefurquin 2014-10-29 18:21:43