Objective-C邊學邊記-11:Foundation Kit快速教程之 綜合樣本(尋找某類型的檔案)

來源:互聯網
上載者:User

7.綜合樣本:尋找檔案
程式功能:尋找主目錄中某類型(.jpg)檔案並輸出找到的檔案清單。
NSFileManager提供對檔案系統的操作,如建立目錄、刪除檔案、移動檔案或者擷取檔案資訊。在這個例子裡,將使用NSFileManager建立NSdirectoryEnumerator來遍曆檔案的階層。

使用了兩種方法遍曆:俺索引枚舉 和 快速枚舉 (見注釋說明):

 1 //
2  // Main.m
3 // FileWalker
4 // 尋找主目錄中某類型(.jpg)檔案並輸出找到的檔案清單。
5 //
6 // Created by Elf Sundae on 10/23/10.
7 // Copyright 2010 Elf.Sundae(at)Gmail.com. All rights reserved.
8 //
9 #import <Foundation/Foundation.h>
10
11 int main (int argc, const char * argv[]) {
12 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
13
14 // 建立NSFileManager
15 NSFileManager *fileManager = [NSFileManager defaultManager];
16 // 指定目錄為主目錄(~):(/Users/ElfSundae)
17 // stringByExpandingTildeInPath方法將路徑展開為fullpath
18 NSString *home = [@"~" stringByExpandingTildeInPath];
19 // 將路徑字串傳給檔案管理工具
20 //An NSDirectoryEnumerator object enumerates
21 //the contents of a directory, returning the
22 //pathnames of all files and directories contained
23 //within that directory. These pathnames are relative
24 //to the directory.
25 //You obtain a directory enumerator using
26 //NSFileManager’s enumeratorAtPath: method.
27
28 //* NSDirectoryEnumerator *direnum=[fileManager enumeratorAtPath:home];
29 //
30 // // 可以在迭代中直接輸出路徑。
31 // // 這裡先儲存到數組中再輸出
32 // NSMutableArray *files = [NSMutableArray arrayWithCapacity:42];
33 //
34 // NSString *fileName;
35 // while (fileName = [direnum nextObject]) {
36 // if ([[fileName pathExtension] isEqualTo:@"jpg"]) {
37 // [files addObject:fileName];
38 // }
39 //* }
40
41 // 或者使用快速枚舉迭代
42 NSMutableArray *files = [NSMutableArray arrayWithCapacity:42];
43 for (NSString *fileName in [fileManager enumeratorAtPath:home])
44 {
45 if ([[fileName pathExtension] isEqualTo:@"jpg"]) {
46 [files addObject:fileName];
47 }
48 }
49
50
51 //* NSEnumerator *jpgFiles = [files objectEnumerator];
52 // while (fileName = [jpgFiles nextObject]) {
53 // NSLog(@"%@",fileName);
54 //* }
55
56 // 或者用快速枚舉輸出
57 for ( NSString *jpg in files)
58 {
59 NSLog(@"%@",jpg);
60 }
61
62
63
64 [pool drain];
65 return 0;
66 }
67

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.