Thursday, May 9, 2013

NSDictionary NSFilePosixPermissions example ios


filePosixPermissions - NSFilePosixPermissions

Returns the value for the key NSFilePosixPermissions.
- (NSUInteger)filePosixPermissions
Return Value
The value, as an unsigned long, for the key NSFilePosixPermissions, or 0 if the dictionary doesn’t have an entry for the key.
Discussion
This and the other file... methods are for use with a dictionary, such as those returned from the methodsfileAttributesAtPath:traverseLink: (NSFileManager), directoryAttributes(NSDirectoryEnumerator), and fileAttributes (NSDirectoryEnumerator), that represents the POSIX attributes of a file or directory. This method returns the file’s permissions.
Example of [NSDictionary NSFilePosixPermissions]
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
NSDict *attribs = [fm attributesOfItemAtPath:[file path] error:&error];
int permissions = [[attribs objectForKey:@"NSFilePosixPermissions"] intValue];
permissions |= (S_IRSUR | S_IRGRP | S_IROTH);
NSDict *newattribs = [NSDict dictionaryWithObject:[NSNumber numberWithInt:permissions]
                                           forKey:NSFilePosixPermissions];
[fm setAttributes:dict ofItemAtPath:[file path] error:&error];

Example of [NSDictionary NSFilePosixPermissions]
[attributes setValue:[NSNumber numberWithShort:0777] 
             forKey:NSFilePosixPermissions]; // chmod permissions 777
Example of [NSDictionary NSFilePosixPermissions]
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 

//Prefixing zero is octal.
int readPermission = 04;
int writePermission = 02;
int executePermission = 01;

//End multiplication is to shift digits left.
int owner = (readPermission | writePermission | executePermission) * (8 * 8);   7
int group = (readPermission)                                       * (8);       4 
int other = (executePermission);                                                1

int permissions = owner + group + other;  //0771

[dict setObject:[NSNumber numberWithInt:permissions] forKey:NSFilePosixPermissions]; 

NSError *error = nil;
[[NSFileManager defaultManager] setAttributes:dict ofItemAtPath:[file path] error:&error];