0

In java I have something like this:

String data = "someFile.txt";
InputStream fin = Thread.currentThread().getContextClassLoader()
                                      .getResourceAsStream(data);

It basically initializes fin with the contents of a text file.

I am trying to convert this java code to objectiveC and I am really lost as how to do it for the second line i.e what is the equivalent of Thread.currentThread().getContextClassLoader().getResourceAsStream(data) in objectiveC ?

NOTE: I can't directly read the file onto the InputStream as the data is globally provided in a string variable.

I am new to objectiveC and sorry if this is trivial but any help would be much appreciated.

Sibir
  • 313
  • 2
  • 6
  • 20

1 Answers1

5

Create NSData from NSString.

Then create NSInputStream from NSData

NSInputStream* is = [NSInputStream inputStreamWithData:[str dataUsingEncoding:NSUTF8StringEncoding]];
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Cy-4AH
  • 4,370
  • 2
  • 15
  • 22
  • Slightly shorter: `[NSInputStream inputStreamWithData:[str dataUsingEncoding:NSUTF8StringEncoding]]` – Martin R Aug 21 '14 at 10:00
  • I got the technique but actually the text file is in unicode, so will `NSUTF8StringEncoding` cause any problems? – Sibir Aug 21 '14 at 10:18
  • Can I use it like this: `[NSInputStream inputStreamWithData: str]` without using the encoding? @MartinR – Sibir Aug 21 '14 at 10:27
  • 1
    @Sibir, you can use any other encoding as you wish. For example `NSUnicodeStringEncoding`. And no, you can't use it without encoding, because `initStreamWithData:` waits for `NSData` object. `NSString` is n't inherited from `NSData`, so you need type conversion. – Cy-4AH Aug 21 '14 at 10:40