Saturday, June 1, 2013

NSData initWithContentsOfFile options error example in Objective C (iOS).


NSData initWithContentsOfFile options error

Returns a data object initialized by reading into it the data from the file specified by a given path.

- (id)initWithContentsOfFile:(NSString *)path options:(NSDataReadingOptions)mask error:(NSError **)errorPtr

Parameters of [NSData initWithContentsOfFile options error]
path
The absolute path of the file from which to read data.
mask
A mask that specifies options for reading the data. Constant components are described in “NSDataReadingOptions”.
errorPtr
If an error occurs, upon return contains an NSError object that describes the problem.

Return Value of [NSData initWithContentsOfFile options error]
A data object initialized by reading into it the data from the file specified by path. The returned object might be different than the original receiver.

NSData initWithContentsOfFile options error example.
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self createEditableCopyOfDatabaseIfNeeded];

    NSString *path = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"testList.plist"];

    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
if (data == nil) {
    NSLog(@"yes nil");
}
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    parser.delegate = self;
    [parser parse];

}

Example of [NSData initWithContentsOfFile options error].
-(FileHash*) hashFileByName :(NSString*) filePath{

    NSAutoreleasePool *innerpool = [[NSAutoreleasePool alloc]init];

    //NSData* inputData = [inputStr dataUsingEncoding:NSUTF8StringEncoding];
    NSData* inputData = [[[NSData alloc]initWithContentsOfFile:filePath] autorelease];
    unsigned char outputData[CC_SHA512_DIGEST_LENGTH];
    CC_SHA512([inputData bytes], [inputData length], outputData);

    NSMutableString* hashStr = [NSMutableString string];
    int i = 0;
    for (i = 0; i < CC_SHA512_DIGEST_LENGTH; ++i)
     [hashStr appendFormat:@"%02x", outputData[i]];


    [innerpool drain];

    //NSLog(@"%@ hash : %@",filePath,hashStr);

    FileHash *hash = [[[FileHash alloc]init]autorelease];
    [hash setFileHash:hashStr];
    [hash setFilePath:filePath];

    return hash;
}

NSData initWithContentsOfFile options error example.
- (UIImage *)imageFromDiskForURL:(NSString *)url
{
    NSData *data = [[NSData alloc] initWithContentsOfFile:cachePathForURL(url) options:0 error:NULL];
    UIImage *i = [[[UIImage alloc] initWithData:data] autorelease];
    [data release];
    return i;
}

End of NSData initWithContentsOfFile options error example article.