Search code examples
objective-cxcodestringmacosnsfilemanager

.m file to string


I am trying to convert a .m file to string. I will search for files in a folder and then want to use each of its contents as a string. This is the code I am using:

- (IBAction)searchAction:(id)sender {

    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *dirContents = [fm contentsOfDirectoryAtPath:folderLabel.stringValue error:nil];
    NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.m'"];
    NSArray *onlyMs = [dirContents filteredArrayUsingPredicate:fltr];

    for (int i=0; i<[onlyMs count]; i++) {

        NSString* text = [[NSString alloc] initWithContentsOfFile:[onlyMs objectAtIndex:i]
                                            encoding:NSUTF8StringEncoding
                                            error:nil];
        NSLog(@"string: %@", text);

    }        
}

2013-02-13 02:38:05.700 LocalizedStringSearch[19001:303] string: (null)

Except here, all the log is returning is null even though it will find all the .m file correctly.

Anyone know what I'm doing wrong?

Thanks a lot!


Solution

    1. I think contentsOfDirectoryAtPath: gives you an array of filenames only, not full path names, so you need to prepend the path before you open files. EDIT: I think I might be confusing that with enumeratorAtPath:... if so continue using the filenames you have rather than appending them to the original folder name.

    2. Here's an example (untested):

      NSString *fullPath = [folderLabel.stringValue stringByAppendingPathComponent:[onlyMs objectAtIndex:i];
      NSError *error = nil;
      NSString *text = [[NSString alloc] initWithContentsofFile:fullPath
                                                       encoding:NSUTF8StringEncoding
                                                          error:&error];
      
      if (text == nil)
          NSLog(@"%@", error);
      else
          NSLog(@"%@", text);
      
    3. The above will only work if the files actually are encoded using UTF-8. If you are unsure of the encoding, you can let the framework try and figure it out for you with:

      NSString *fullPath = [folderLabel.stringValue stringByAppendingPathComponent:[onlyMs objectAtIndex:i];
      NSError *error = nil;
      NSStringEncoding enc;
      NSString *text = [[NSString alloc] initWithContentsofFile:fullPath
                                                   usedEncoding:&enc
                                                          error:&error];
      
      if (text == nil)
          NSLog(@"%@", error);
      else
          NSLog(@"%@", text);