2010-04-25 27 views
5

tôi có mã này dưới đây:đọc Text File tại văn bản Folder - Iphone SDK

NSString *fileName = [[NSUserDefaults standardUserDefaults] objectForKey:@"recentDownload"]; 
    NSString *fullPath = [NSBundle pathForResource:fileName ofType:@"txt" inDirectory:[NSHomeDirectory() stringByAppendingString:@"/Documents/"]]; 
    NSError *error = nil; 

    [textViewerDownload setText:[NSString stringWithContentsOfFile:fullPath encoding: NSUTF8StringEncoding error:&error]]; 
  • textviewerdownloadtextview hiển thị văn bản từ tập tin. Tên tệp thực được lưu trữ trong một NSUserDefault được gọi là recentDownload.

  • Khi tôi tạo điều này, tôi nhấp vào số button dưới đây và ứng dụng của tôi crashes.

  • Có điều gì sai với cú pháp hoặc lỗi đơn giản không?

+0

Nếu có vấn đề với cú pháp, mã của bạn sẽ không biên dịch; bạn sẽ không đến giai đoạn chạy nó và thấy nó sụp đổ. Để gỡ lỗi một sự cố, hãy sử dụng trình gỡ lỗi; nó sẽ cho bạn biết làm thế nào bạn bị rơi và ở đâu. –

Trả lời

9

Lớp NSBundle được sử dụng để tìm mọi thứ trong gói ứng dụng của bạn, nhưng thư mục Documents nằm ngoài gói, vì vậy cách bạn tạo đường dẫn sẽ không hoạt động. Hãy thử điều này thay vì:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                NSUserDomainMask, 
                YES); 

NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:@"recentDownload.txt"]; 
+0

Ok Tôi đã thay đổi một số mã hóa .. Ứng dụng của tôi vẫn bị treo .. Đây là mã theo IBAction của tôi: http://www.heliotop.org/code.rtf Ngoài ra làm cách nào tôi thực hiện câu lệnh if, nếu tập tin gần đây không phải là một tập tin có phần mở rộng "txt", nó sẽ trả lại, và nếu sau đó nó được tạo thành một hành động. – lab12

6
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSString *myPathDocs = [documentsDirectory stringByAppendingPathComponent:@"myfile.txt"]; 

    if (![[NSFileManager defaultManager] fileExistsAtPath:myPathDocs]) 
    { 
     NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:@"myfile" ofType:@"txt"]; 
     NSFileManager *fileManager = [NSFileManager defaultManager]; 
     [fileManager copyItemAtPath:myPathInfo toPath:myPathDocs error:NULL]; 
    }  

    //Load from File 
NSString *myString = [[NSString alloc] initWithContentsOfFile:myPathDocs encoding:NSUTF8StringEncoding error:NULL]; 

này làm việc cho tôi

Dù sao, cảm ơn tất cả các bạn ..

2

Đối với đọc/ghi từ tập tin văn bản kiểm tra url này.

+0

Đảm bảo bạn đặt cờ boolean “UIFileSharingEnabled” thành 'YES' trong info.plist của bạn. – msgambel

Các vấn đề liên quan