0

I have a file with multiple lines, and I'm trying to read it by converting it into a NSString. I've looked here: How to read data from NSFileHandle line by line?, but that didn't work for this situation because it shouldn't be a loop; I'm not trying to read the whole thing, just one line.

Example File:

ThingsIWantToRead
Blah Blah Blah
Blah Blah BLah
Ect. Ect.

I think I have successfully gotten the program to each line of a file into an array, but now I can't get the first object of the array into a NSString. Apple's documentation on the getObjects:range: for NSArray (https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html) was before ARC, so Xcode gives me errors about translating pointer type void * to __ strong id * and such.

           //This gets first line of file and sets it as a NSString usernameCaseSensitive
            NSString * fileHandler = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
            NSArray * fileContents = [fileHandler componentsSeparatedByString:@"\n"];
            //Set the NSRange
            NSRange range = NSMakeRange (1, 1);
            id * objects;
            objects = malloc(sizeof(id) * range.length);
            NSString * firstLine = [fileContents getObjects:objects range: range];
Community
  • 1
  • 1
Eliza Wilson
  • 1,031
  • 1
  • 13
  • 38

1 Answers1

1

Well if your array is correct, just get the first object in it :

NSString * firstLine = fileContents[0];
Mario
  • 4,530
  • 1
  • 21
  • 32
  • That was considerably easier then the documentation... Do I just have [1] if I wanted the NSString to be the contents of the second object? – Eliza Wilson Jul 30 '13 at 22:06
  • 1
    Yes. It is the new subscripting notation to access an object in the array. It is equivalent to calling `[myArray objectAtIndex: index]`. Be careful to make sanity checks to catch out of bound errors though. – Mario Jul 30 '13 at 22:33