Monday, April 22, 2013

NSFileManager setAttributes example ios


setAttributes :ofItemAtPath:error:

Sets the attributes of the specified file or directory.
- (BOOL)setAttributes:(NSDictionary *)attributes ofItemAtPath:(NSString *)path error:(NSError **)error
Parameters
attributes
A dictionary containing as keys the attributes to set for path and as values the corresponding value for the attribute. You can set the following attributes:NSFileBusyNSFileCreationDateNSFileExtensionHidden,NSFileGroupOwnerAccountIDNSFileGroupOwnerAccountName,NSFileHFSCreatorCodeNSFileHFSTypeCodeNSFileImmutable,NSFileModificationDateNSFileOwnerAccountID,NSFileOwnerAccountNameNSFilePosixPermissions. You can change single attributes or any combination of attributes; you need not specify keys for all attributes.[NSFileManager setAttributes]
path
The path of a file or directory.
error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information.
Return Value
YES if all changes succeed. If any change fails, returns NO, but it is undefined whether any changes actually occurred.
Discussion of [NSFileManager setAttributes]
As in the POSIX standard, the app either must own the file or directory or must be running as superuser for attribute changes to take effect. The method attempts to make all changes specified in attributes and ignores any rejection of an attempted modification. If the last component of the path is a symbolic link it is traversed.
The NSFilePosixPermissions value must be initialized with the code representing the POSIX file-permissions bit pattern. NSFileHFSCreatorCode andNSFileHFSTypeCode will only be heeded when path specifies a file.
Example of [NSFileManager setAttributes]

NSString *path = @"/The/root/directory";
NSDictionary *attributes;   // Assume that this is already setup


NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
NSArray *subPaths = [fileManager subpathsAtPath:path];
for (NSString *aPath in subPaths) {
    BOOL isDirectory;
    [fileManager fileExistsAtPath:aPath isDirectory:&isDirectory];
    if (isDirectory) {
        // Change the permissions on the directory here
        NSError *error = nil;
        [fileManager setAttributes:attributes ofItemAtPath:aPath error:error];
        if (error) {
            // Handle the error
        }
    }
}