Monday, April 04, 2011

Xcode snippet #1: Reading the contents of a directory

Below you will find a code snippet which reads the contents of a specific directory (in this case the documents directory) from your device. It looks for file with has a suffix .list, stripes the filename from it with the substringToIndex method and adds that name to another array.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; 
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:nil];
for (NSString *dir in dirContents) {
  if ([dir hasSuffix:@".list"]) {
      NSRange range = [dir rangeOfString:@"."];
      NSString *name = [dir substringToIndex:range.location];
      if (![name isEqualToString:@""]) {
          MyListItem *listItem = [[MyListItem alloc] init];
          listItem.name = name;
          [lists addObject:listItem];
          [listItem release];
      }
  }
}