Sunday, April 21, 2013

NSFileManager attributesOfItemAtPath example objc


attributesOfItemAtPath:error:

Returns the attributes of the item at a given path.
- (NSDictionary *)attributesOfItemAtPath:(NSString *)path error:(NSError **)error
Parameters
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 of [NSFileManager attributesOfItemAtPath]
An NSDictionary object that describes the attributes (file, directory, symlink, and so on) of the file specified by path, or nil if an error occurred. The keys in the dictionary are described in “File Attribute Keys”.
Special Considerations for [NSFileManager attributesOfItemAtPath]
If the item at the path is a symbolic link—that is, the value of the NSFileType key in the attributes dictionary is NSFileTypeSymbolicLink—you can use the destinationOfSymbolicLinkAtPath:error:method to retrieve the path of the item pointed to by the link. You can also use thestringByResolvingSymlinksInPath method of NSString to resolve links in the path before retrieving the item’s attributes.
As a convenience, NSDictionary provides a set of methods (declared as a category on NSDictionary) for quickly and efficiently obtaining attribute information from the returned dictionary:fileGroupOwnerAccountNamefileModificationDatefileOwnerAccountName,filePosixPermissionsfileSizefileSystemFileNumberfileSystemNumber, and fileType.
Example of [NSFileManager attributesOfItemAtPath]

- (IBAction)startCopy:(id)sender;
{
NSError *attributeserror = nil;

NSString *accountsourcestring = [sourceFilePath stringValue];
NSString *accountsourcestringpath =[accountsourcestring stringByStandardizingPath];

// Use the NSFileManager to obtain the size of our source file in bytes.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSDictionary *sourceAttributes = [fileManager     attributesOfItemAtPath:accountsourcestringpath error:&attributeserror];
NSNumber *sourceFileSize= [sourceAttributes objectForKey:NSFileSize];
long long fileSize = [sourceFileSize longLongValue];

NSLog(@"Filesize = %lld", fileSize);
NSLog(@"sourcefilepath: %@", accountsourcestring);

if ((sourceFileSize = [sourceAttributes objectForKey:NSFileSize]) )
{
    // Set the max value to our source file size
    [progressIndicator setMaxValue:(double)[sourceFileSize unsignedLongLongValue]];
}
    else
{
    // Couldn't get the file size so we need to bail.
    NSLog(@"Unable to obtain size of file being copied. Error %@ Source file size: %@,   sourceAttributes: %@", attributeserror, sourceFileSize, sourceAttributes);
    return;
}