Saturday, June 1, 2013

NSData initWithContentsOfFile example in Objective C (iOS).


NSData initWithContentsOfFile

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

- (id)initWithContentsOfFile:(NSString *)path

Parameters
path
The absolute path of the file from which to read data.

Return Value
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.

Discussion of [NSData initWithContentsOfFile]
This method is equivalent to initWithContentsOfFile:options:error: with no options.

NSData initWithContentsOfFile 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].
-(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 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 example article.