Advertisement
dinophanhk

[Obj-C] NSFileManager

Jun 18th, 2014
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. //  KHTNViewController.m
  3. //  NSFileManager Sample
  4. //
  5. //  Created by Dino Phan on 6/18/14.
  6. //  Copyright (c) 2014 Dino Phan. All rights reserved.
  7. //
  8.  
  9. #import "KHTNViewController.h"
  10.  
  11. @interface KHTNViewController ()
  12.  
  13. @property (strong, nonatomic) NSFileManager *fileManager;
  14. @property (strong, nonatomic) NSString *stringPath;
  15. @property (strong, nonatomic) NSString *contentOfFile;
  16.  
  17. @end
  18.  
  19. @implementation KHTNViewController
  20. @synthesize fileManager, stringPath, contentOfFile;
  21.  
  22. - (void)viewDidLoad
  23. {
  24.     [super viewDidLoad];
  25.  
  26.     fileManager = [NSFileManager defaultManager];
  27.     stringPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
  28.     contentOfFile = @"Hello World!";
  29.     NSString *pathOfFile = [stringPath stringByAppendingPathComponent:@"data.txt"];
  30.     NSError *error = [[NSError alloc] init];
  31.    
  32.     // Create a file
  33.     if ([contentOfFile writeToFile:pathOfFile atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
  34.         NSLog(@"'%@' has successfully wrote!", pathOfFile);
  35.     } else {
  36.         NSLog(@"Error: %@", [error debugDescription]);
  37.     }
  38.    
  39.     // Read content in file
  40.     NSString *getContent = [[NSString alloc] initWithContentsOfFile:pathOfFile encoding:NSUTF8StringEncoding error:nil];
  41.     NSLog(@"%@", getContent);
  42.    
  43.     // Remove a file from Document dir
  44.     if ([fileManager removeItemAtPath:pathOfFile error:&error]) {
  45.         NSLog(@"'%@' removed!", pathOfFile);
  46.     } else {
  47.         NSLog(@"Error: %@", [error debugDescription]);
  48.     }
  49.    
  50.     // Get boolean if file exist in documents folder
  51.     if ([fileManager fileExistsAtPath:pathOfFile]) {
  52.         NSLog(@"File exist!");
  53.     } else {
  54.         NSLog(@"File isn't exist!");
  55.     }
  56.    
  57.     // List files in root
  58.     NSArray *fileListAtRoot = [fileManager contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@""] error:nil];
  59.     NSString *fileNameInList = [[NSString alloc] init];
  60.    
  61.     for (fileNameInList in fileListAtRoot) {
  62.         NSLog(@"%@", fileNameInList);
  63.     }
  64.    
  65. - (void)didReceiveMemoryWarning
  66. {
  67.     [super didReceiveMemoryWarning];
  68.     // Dispose of any resources that can be recreated.
  69. }
  70.  
  71. @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement