- 浏览: 340213 次
- 性别:
- 来自: 武汉
文章分类
最新评论
-
leslie89757:
[img][img][img][img][img][img][ ...
CocoaPods 安装使用 -
hanmeizhi:
very useful to me. Thanks
Dismissing MPMoviePlayerViewController the right way -
luzj:
这个考虑不周全, 在iOS5的键盘高度就不是这个值了,这样写死 ...
UITextView: move view when keyboard appears -
xjg19870111:
不错。
objective-c NSString 常用操作 -
juedui0769:
现在已经不行了!
android源码下载
Working with Directories in Objective-C
original address: http://www.techotopia.com/index.php/Working_with_Directories_in_Objective-C
A key element of gaining proficiency in any programming language involves the ability to work with files and file systems. The level of difficulty in working with files varies from very easy to hard, depending on the programming language concerned. The C programming language, on which Objective-C is based, tended to make file handling a little hard relative to the standards of today's programmer friendly object oriented languages. The good news for Objective-C developers is that the Foundation Framework includes a number of classes designed specifically to make the task of working with files and directories as straightforward as possible.
In this chapter we will look at these classes and provide examples of how use them to perform some basic directory operations from within an Objective-C program. In Working with Files in Objective-C we will take a close look at working with files using these classes.
The Objective-C NSFileManager, NSFileHandle and NSData Classes
The Foundation Framework provides three classes that are indispensable when it comes to working with files and directories:
NSFileManager - The NSFileManager class can be used to perform basic file and directory operations such as creating, moving, reading and writing files and reading and setting file attributes. In addition, this class provides methods for, amongst other tasks, identifying the current working directory, changing to a new directory, creating directories and listing the contents of a directory.
NSFileHandle - The NSFileHandle class is provided for performing lower level operations on files, such as seeking to a specific position in a file and reading and writing a file's contents by a specified number of byte chunks and appending data to an existing file.
NSData - The NSData class provides a useful storage buffer into which the contents of a file may be read, or from which data may be written to a file.
Understanding Pathnames in Objective-C
When using the above classes, pathnames are defined using the UNIX convention. As such each component of a path is separated by a forward slash (/). Paths that do not begin with a slash are interpreted to be relative to a current working directory. For example, if the current working directory is /home/objc and the path name is myapp/example.m then the file is considered to have a full pathname of /home/objc/myapp/example.m.
In addition, the home directory of the current user can be represented using the tilde (~) character. For example the pathname ~/example.m references a file named example.m located in the home directory of the current user. The home directory of another user may be referenced by prefixing the user name with a ~. For example, ~john/demo.m references a file located in the home directory of a user named john.
Obtaining a Reference to the Default NSFileManager Object
The NSFileManager class contains a class method named defaultManager that is used to obtain a reference to the application’s default file manager instance:
In the above example we have declared a variable named filemgr to point to an object of type NSFileManager, and then requested a pointer to the application’s file manager and assigned it to the variable. Having obtained the object reference we can begin to use it to work with files and directories.
Identifying the Current Working Directory
The current working directory may be identified using the currentDirectoryPath instance method of our NSFileManager object. The current path is returned from the method in the form of an NSString object:
Changing to a Different Directory
The current working directory of a running Objective-C program can be changed with a call to the changeCurrentDirectoryPath method. The destination directory path is passed as an argument to the instance method in the form of an NSString object. Note that this method returns a boolean YES or NO result to indicate if the requested directory change was successful for not:
Creating a New Directory
A new directory is created using the createDirectoryAtURL instance method, this time passing through the through the pathname of the new directory as an argument in the form of an NSURL object. This method also takes additional arguments in the form of a set of attributes for the new directory and a Boolean value indicating whether or not intermediate directories should be created if they do not already exist. Specifying nil will use the default attributes:
The createDirectoryAtURL method returns a Boolean result indicating the success or otherwise of the operation.
Deleting a Directory
An existing directory may be removed from the file system using the removeItemAtPath method, passing though the path of the directory to be removed as an argument:
Renaming or Moving a File or Directory
An existing file or directory may be moved (also known as renaming) using the moveItemAtURL method. This method takes the source and destination pathnames as arguments in the form of NSURL objects and requires that the destination path not already exist. If the target exists, a boolean NO result is returned by the method to indicate failure of the operation:
Getting a Directory File Listing
A listing of the files contained within a specified directory can be obtained using the contentsOfDirectoryAtPath method. This method takes the directory pathname as an argument and returns an NSArray object containing the names of the files and sub-directories in that directory:
When executed as part of a program, the above code excerpt will display a listing of all the files located in the /tmp directory.
Getting the Attributes of a File or Directory
The attributes of a file or directory can be obtained using the attributesOfItemAtPath method. This takes as arguments the path of the directory and an optional NSError object into which information about any errors will be placed (may be specified as NULL if this information is not required). The results are returned in the form of an NSDictionary dictionary object (for details of working with dictionary objects refer to Objective-C Dictionary Objects). The keys for this dictionary are as follows:
NSFileType
NSFileTypeDirectory
NSFileTypeRegular
NSFileTypeSymbolicLink
NSFileTypeSocket
NSFileTypeCharacterSpecial
NSFileTypeBlockSpecial
NSFileTypeUnknown
NSFileSize
NSFileModificationDate
NSFileReferenceCount
NSFileDeviceIdentifier
NSFileOwnerAccountName
NSFileGroupOwnerAccountName
NSFilePosixPermissions
NSFileSystemNumber
NSFileSystemFileNumber
NSFileExtensionHidden
NSFileHFSCreatorCode
NSFileHFSTypeCode
NSFileImmutable
NSFileAppendOnly
NSFileCreationDate
NSFileOwnerAccountID
NSFileGroupOwnerAccountID
For example, we can extract the creation date, file type and POSIX permissions for the /tmp directory using the following code excerpt:
When executed on a Mac OS X system, we can expect to see the following output (note that /tmp on a Mac OS X system is a symbolic link to private/tmp):
Created on 2009-01-14 07:34:32 -0500
File type NSFileTypeSymbolicLink
POSIX Permissions 493
original address: http://www.techotopia.com/index.php/Working_with_Directories_in_Objective-C
A key element of gaining proficiency in any programming language involves the ability to work with files and file systems. The level of difficulty in working with files varies from very easy to hard, depending on the programming language concerned. The C programming language, on which Objective-C is based, tended to make file handling a little hard relative to the standards of today's programmer friendly object oriented languages. The good news for Objective-C developers is that the Foundation Framework includes a number of classes designed specifically to make the task of working with files and directories as straightforward as possible.
In this chapter we will look at these classes and provide examples of how use them to perform some basic directory operations from within an Objective-C program. In Working with Files in Objective-C we will take a close look at working with files using these classes.
The Objective-C NSFileManager, NSFileHandle and NSData Classes
The Foundation Framework provides three classes that are indispensable when it comes to working with files and directories:
NSFileManager - The NSFileManager class can be used to perform basic file and directory operations such as creating, moving, reading and writing files and reading and setting file attributes. In addition, this class provides methods for, amongst other tasks, identifying the current working directory, changing to a new directory, creating directories and listing the contents of a directory.
NSFileHandle - The NSFileHandle class is provided for performing lower level operations on files, such as seeking to a specific position in a file and reading and writing a file's contents by a specified number of byte chunks and appending data to an existing file.
NSData - The NSData class provides a useful storage buffer into which the contents of a file may be read, or from which data may be written to a file.
Understanding Pathnames in Objective-C
When using the above classes, pathnames are defined using the UNIX convention. As such each component of a path is separated by a forward slash (/). Paths that do not begin with a slash are interpreted to be relative to a current working directory. For example, if the current working directory is /home/objc and the path name is myapp/example.m then the file is considered to have a full pathname of /home/objc/myapp/example.m.
In addition, the home directory of the current user can be represented using the tilde (~) character. For example the pathname ~/example.m references a file named example.m located in the home directory of the current user. The home directory of another user may be referenced by prefixing the user name with a ~. For example, ~john/demo.m references a file located in the home directory of a user named john.
Obtaining a Reference to the Default NSFileManager Object
The NSFileManager class contains a class method named defaultManager that is used to obtain a reference to the application’s default file manager instance:
NSFileManager *filemgr; filemgr = [NSFileManager defaultManager];
In the above example we have declared a variable named filemgr to point to an object of type NSFileManager, and then requested a pointer to the application’s file manager and assigned it to the variable. Having obtained the object reference we can begin to use it to work with files and directories.
Identifying the Current Working Directory
The current working directory may be identified using the currentDirectoryPath instance method of our NSFileManager object. The current path is returned from the method in the form of an NSString object:
NSFileManager *filemgr; NSString *currentpath; filemgr = [NSFileManager defaultManager]; currentpath = [filemgr currentDirectoryPath]; NSLog (@"Current directory is %@", currentpath);
Changing to a Different Directory
The current working directory of a running Objective-C program can be changed with a call to the changeCurrentDirectoryPath method. The destination directory path is passed as an argument to the instance method in the form of an NSString object. Note that this method returns a boolean YES or NO result to indicate if the requested directory change was successful for not:
NSFileManager *filemgr; NSString *currentpath; filemgr = [NSFileManager defaultManager]; currentpath = [filemgr currentDirectoryPath]; NSLog (@"Current directory is %@", currentpath); if ([filemgr changeCurrentDirectoryPath: @"/temp/mydir"] == NO) NSLog (@"Cannot change directory."); currentpath = [filemgr currentDirectoryPath]; NSLog (@"Current directory is %@", currentpath);
Creating a New Directory
A new directory is created using the createDirectoryAtURL instance method, this time passing through the through the pathname of the new directory as an argument in the form of an NSURL object. This method also takes additional arguments in the form of a set of attributes for the new directory and a Boolean value indicating whether or not intermediate directories should be created if they do not already exist. Specifying nil will use the default attributes:
NSFileManager *filemgr; filemgr = [NSFileManager defaultManager]; NSURL *newDir = [NSURL fileURLWithPath:@"/tmp/mynewdir"]; [filemgr createDirectoryAtURL: newDir withIntermediateDirectories:YES attributes: nil error:nil];
The createDirectoryAtURL method returns a Boolean result indicating the success or otherwise of the operation.
Deleting a Directory
An existing directory may be removed from the file system using the removeItemAtPath method, passing though the path of the directory to be removed as an argument:
NSFileManager *filemgr; filemgr = [NSFileManager defaultManager]; [filemgr removeItemAtPath: @"/tmp/mynewdir" handler: nil];
Renaming or Moving a File or Directory
An existing file or directory may be moved (also known as renaming) using the moveItemAtURL method. This method takes the source and destination pathnames as arguments in the form of NSURL objects and requires that the destination path not already exist. If the target exists, a boolean NO result is returned by the method to indicate failure of the operation:
NSFileManager *filemgr; filemgr = [NSFileManager defaultManager]; NSURL *oldDir = [NSURL fileURLWithPath:@"/tmp/mynewdir"]; NSURL *newDir = [NSURL fileURLWithPath:@"/tmp/mynewdir2"]; [filemgr moveItemAtURL: oldDir toURL: newDir error: nil];
Getting a Directory File Listing
A listing of the files contained within a specified directory can be obtained using the contentsOfDirectoryAtPath method. This method takes the directory pathname as an argument and returns an NSArray object containing the names of the files and sub-directories in that directory:
NSFileManager *filemgr; NSString *currentpath; NSArray *filelist; int count; int i; filemgr = [NSFileManager defaultManager]; filelist = [filemgr contentsOfDirectoryAtPath: @"/tmp" error: nil]; count = [filelist count]; for (i = 0; i < count; i++) NSLog (@"%@", [filelist objectAtIndex: i]);
When executed as part of a program, the above code excerpt will display a listing of all the files located in the /tmp directory.
Getting the Attributes of a File or Directory
The attributes of a file or directory can be obtained using the attributesOfItemAtPath method. This takes as arguments the path of the directory and an optional NSError object into which information about any errors will be placed (may be specified as NULL if this information is not required). The results are returned in the form of an NSDictionary dictionary object (for details of working with dictionary objects refer to Objective-C Dictionary Objects). The keys for this dictionary are as follows:
NSFileType
NSFileTypeDirectory
NSFileTypeRegular
NSFileTypeSymbolicLink
NSFileTypeSocket
NSFileTypeCharacterSpecial
NSFileTypeBlockSpecial
NSFileTypeUnknown
NSFileSize
NSFileModificationDate
NSFileReferenceCount
NSFileDeviceIdentifier
NSFileOwnerAccountName
NSFileGroupOwnerAccountName
NSFilePosixPermissions
NSFileSystemNumber
NSFileSystemFileNumber
NSFileExtensionHidden
NSFileHFSCreatorCode
NSFileHFSTypeCode
NSFileImmutable
NSFileAppendOnly
NSFileCreationDate
NSFileOwnerAccountID
NSFileGroupOwnerAccountID
For example, we can extract the creation date, file type and POSIX permissions for the /tmp directory using the following code excerpt:
NSFileManager *filemgr; NSDictionary *attribs; filemgr = [NSFileManager defaultManager]; attribs = [filemgr attributesOfItemAtPath: @"/tmp" error: NULL]; NSLog (@"Created on %@", [attribs objectForKey: NSFileCreationDate]); NSLog (@"File type %@", [attribs objectForKey: NSFileType]); NSLog (@"POSIX Permissions %@", [attribs objectForKey: NSFilePosixPermissions]);
When executed on a Mac OS X system, we can expect to see the following output (note that /tmp on a Mac OS X system is a symbolic link to private/tmp):
Created on 2009-01-14 07:34:32 -0500
File type NSFileTypeSymbolicLink
POSIX Permissions 493
发表评论
-
IOS7.1 企业应用 证书无效 已解决
2014-05-10 10:53 774http://www.cocoachina.com/bbs/r ... -
xCode Find&Replace快捷键
2013-10-28 10:44 907As for Find & Replace, they ... -
iOS整合zxing需要注意的地方
2013-08-02 23:34 2106Well, at last I got it working. ... -
iOS 自定义Tabbar
2013-07-30 22:55 1191http://www.appcoda.com/ios-prog ... -
Apple Push Notification Service总结
2013-07-29 22:39 1115苹果推送通知服务使用总结 1. 在 Mac 上从 KeyCha ... -
iOS 消息推送原理及实现
2013-07-12 13:40 855链接: http://www.dapps.net/dev/ ... -
GIMP IMAGE MAP
2013-05-29 16:13 853使用GIMP 制作 IMAGE MAP 1. 选择图片,用G ... -
INSPIRATION
2013-05-27 18:21 813http://www.patternsofdesign.co. ... -
iOS 自定义控件系列
2013-05-27 17:09 1481iOS自定义控件 自定义UITableViewCell ht ... -
CocoaPods 使用教程
2013-05-27 14:49 768http://mobile.tutsplus.com/tuto ... -
IOS 开发之设置UIButton的title
2013-05-11 22:03 1207btn.frame = CGRectMake(x, y, wi ... -
REActivityViewController 使用 备忘
2013-04-22 21:38 1058REActivityViewController Out o ... -
VPS配置二级域名
2013-04-18 23:08 7881. 域名解析商配置泛解析 主机记录 * 记录类型 A 2. ... -
ios 开发NewsStand指南
2013-04-13 21:44 1324http://www.viggiosoft.com/blog/ ... -
Python Django mod_wsgi Windows 部署过程 备忘
2013-04-10 18:28 1587部署环境:Windows2003Server 1. 安装Ap ... -
网站迁移 备忘
2013-04-10 14:58 7511. 备份数据库。。。导出的格式和编码要注意 2. 完全导出网 ... -
Windows下命令行查看端口占用
2013-04-09 23:42 723在windows命令行窗口下执行: C:\>netst ... -
带预览功能又可分页的UIScrollView
2013-04-05 12:56 823带预览功能又可分页的UIScrollView http:// ... -
25 iOS App 性能优化
2013-04-05 10:51 695http://www.raywenderlich.com/ ... -
UIScrollView滚动, 中间显示整图, 前后露出部分图
2013-04-04 00:12 1200UIScrollView *scrollowView = [[ ...
相关推荐
随着iOS应用的日益流行,越来越多的开发者希望能够快速上手Objective-C语言。然而,并非所有人都能拥有苹果设备来直接进行开发。因此,在Windows平台上搭建Objective-C开发环境成为了一种可行的选择。本文将详细介绍...
【搭建Objective-C集成开发环境】 Objective-C是一种主要应用于苹果平台的编程语言,尤其在iOS和macOS应用开发中占据核心地位。尽管它主要与苹果的Xcode IDE紧密关联,但在Windows环境下,我们同样可以通过配置其他...
- **Creating Cool Apps:** With a solid foundation in Objective-C and familiarity with Cocoa and Cocoa Touch, you'll be ready to create your own applications. The book provides practical examples and ...
在`Recurse-Directories-in-C-master`这个项目中,可能包含了完整的目录递归示例代码,包括错误处理和更复杂的逻辑,比如排除特定文件类型或者处理软链接。这样的代码可以帮助你理解和学习如何在实际项目中应用目录...
### Windows XP 系统下创建 Objective-C 集成开发环境 #### 概述 本文旨在详细介绍如何在 Windows XP 操作系统中搭建一套基于 GNUstep 和 CodeBlocks 的 Objective-C 集成开发环境(IDE)。该环境对于希望在 ...
**PyPI 官网下载 | clean_directories-1.1.0-py3-none-any.whl** `clean_directories-1.1.0-py3-none-any.whl` 是一个在Python Package Index (PyPI) 上发布的软件包,用于管理项目中的目录。PyPI是Python开发者...
资源来自pypi官网。 资源全名:ldap3_directories-0.2.4-py3-none-any.whl
**Python库ldap3_directories-0.2.4-py3-none-any.whl详解** `ldap3_directories` 是一个Python库,专为处理 Lightweight Directory Access Protocol (LDAP) 目录服务而设计。这个库的版本是0.2.4,它支持Python 3....
在Windows环境下搭建Objective-C开发环境是一项相对复杂的工作,因为Objective-C主要是与苹果的 macOS 和 iOS 平台紧密关联,而这些平台通常使用Xcode作为主要的开发工具。然而,通过一些开源工具,我们可以在...
### Isilon横向扩展NAS在家庭目录和文件共享中的应用 #### 消除NAS孤岛 在现代企业环境中,网络附加存储(Network Attached Storage, NAS)常常成为数据存储的关键组成部分。随着组织规模的扩大和技术的进步,传统的...
### Objective-C 开发环境搭建详解:使用 Codeblocks #### 一、概述 Objective-C 是一种通用、面向对象的编程语言,最初由苹果公司用于 macOS 和 iOS 操作系统的开发。为了能够在计算机上进行 Objective-C 的学习...
将CS106Inc复制到\Microsoft Visual Studio\VC98\Include下,并设置VC的Include directories(在Tools/Options/Directories)加上CS106Inc完整路径. 再复制CS106lib.lib到\Microsoft Visual Studio\VC98\lib目录下。 ...
项目中使用的是1.4.7,作为eclipse的插件装的;后来又在机子上装了个TortoiseSVN 1.6.5。... --skip-unknown-format : skip directories with unknown working copy format and continue the update
以前常常在找让ls单独列出文件或文件夹的方法,基本上都是通过一些shell处理,不过得到的结果一般都没有格式。... -c --count count there are how much files and directories. -h --help show this.
Using built-in specs. Target: arm-none-linux-gnueabi Configured with: /scratch/julian/lite-respin/linux/src/gcc-4.3/configure --build=i686-pc-linux-gnu --host=i686-pc-linux-gnu --target=arm-none-linux...
在IT行业中,目录(Directories)和文件(Files)是计算机操作系统中最基本的组织单元,用于存储和管理数据。本主题将深入探讨这两个概念,以及它们在CSS(Cascading Style Sheets)中的应用。 目录,也被称为...
在Bash中浏览文件和目录 学习目标 用ls shell中的目录文件 使用mv移动或重命名文件和目录 使用cp复制文件 touch创建空文件 用mkdir新建目录 用rm删除文件 介绍 在上一课中,我们学习了如何“导航”文件系统的目录...
在Bash中浏览文件和目录 学习目标 用ls shell中的目录文件 使用mv移动或重命名文件和目录 使用cp复制文件 touch创建空文件 用mkdir新建目录 用rm删除文件 介绍 在上一课中,我们学习了如何“导航”文件系统的目录...
在Bash中浏览文件和目录 学习目标 用ls shell中的目录文件 使用mv移动或重命名文件和目录 使用cp复制文件 touch创建空文件 用mkdir新建目录 用rm删除文件 介绍 在上一课中,我们学习了如何“导航”文件系统的目录...