Reading characters from a file and storing as NSString - objective-c

I'm trying to read in a text file and save character arrays as NSStrings.
For example, if the file contains just the word "Hello" I want to have an NSString containing "Hello"
How can I do this?

NSString *string = [NSString stringWithContentsOfFile:filePath usedEncoding:&encoding error:&error];
filePath should be a string with the path to file
encoding (NSStringEncoding) will contain the encoding used
error (NSError *) will contain an error if one occurs
string will contain the contents of the file or will be nil if an error occurred

You can use the NSString instance method -initWithContentsOfFile:encoding:error: or the 'convenience method' +stringWithContentsOfFile:encoding:error:
In the first instance:
NSString *fileContents = [[NSString alloc] initWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:&error];
In the second:
NSString *fileContents = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:&error];
where
pathToFile is an NSString that is the path to the file you're reading
encoding is one of the NSStringEncoding constants (have a look at the docs)
error is a pointer to an NSError object which is populated by the methods if an error occurs.
The choice between the two depends on whether you want an autoreleased string at the end or not.

you could use something like:
NSString *string = [[NSString alloc] initWithContentsOfFile:#"/path/to/file/goes/here.txt"];
if you know the exact path of the file.

Related

NSJSONSerialization does not produce valid UTF8 string

I have an NSDictionary that I try to convert to JSON using the following code
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:nil];
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
The resulting data object looks good, but the final NSString remains NULL. If I create the NSString with NSASCIIStringEncoding I get a proper string object, but any multibyte UTF8 characters are of course maimed.
Shouldn't dataWithJSONObject always yield valid UTF8 data whenever the function is succesful?
Details: I'm pretty sure the culprit is somewhere in my input data (strings parsed from custom binary format), but there is quite a lot of data and I'm not sure how to efficiently detect where the problem is.

Remove first line in JSON response

I am using the Google Speech API unofficially. If you send it an audio file saying "Test", it will respond with this:
{"result":[]}
{"result":[{"alternative":[{"transcript":"test","confidence":0.88845605},{"transcript":"tests"},{"transcript":"the test"},{"transcript":"text"},{"transcript":"Test"}],"final":true}],"result_index":0}
I need to remove the first line of this response so my parser will not error out.
Is there an official way to remove this first line in the JSON?
I am using Xcode 6.1 (I haven't updated Xcode yet) with the iOS 6.1 SDK.
// Assuming your string looks something like this
NSString *fileContents = #"Bob Smith: 1 (234)-567-8901\nBob Smith: bob#bob.com";
// Lets store the information on each new line in an array
NSArray *lines = [fileContents componentsSeparatedByString:#"\n"];
// The second object will contain the email
NSString *email = [lines objectAtIndex:1];
NSLog(#"%#",email);
NSString* fileRoot = [[NSBundle mainBundle]
pathForResource:#"test" ofType:#"txt"];
NSString* fileContents = [NSString stringWithContentsOfFile:fileRoot
encoding:NSUTF8StringEncoding error:nil];
NSArray* allLinedStrings = [fileContents componentsSeparatedByCharactersInSet:
[NSCharacterSet newlineCharacterSet]];
In this array you can judge if it contains a phoneNumber, str is every element.
NSString *phoneNumber = [str componentsSeparatedByString:#":"][1];
if phoneNumber is a phoneNumber format. Then delete this line.

Converting two double values to String and then making a string using the new strings

I am trying to convert two values to string and then make a new string containing the ones i made earlier so my service can accept them.
NSString *string1 = [ NSString stringWithFormat:#"%f", locationController.dblLatitude];
NSString *string2 = [ NSString stringWithFormat:#"%f", locationController.dblLongitude];
body = [[NSString stringWithFormat:#"geoX#%##geoY#%#", string1, string2] dataUsingEncoding:NSUTF8StringEncoding];
This is the code i am using atm. The problem is that both string1 and string2 appear to be ok but the string named body appears to not working.. :< Any help ?
body is not an NSString instance here, but NSData (because you're using `dataUsingEncoding:".
If you want to see concatenation of stings in system log you should write something like that:
NSString* bodyString = [NSString stringWithFormat:#"geoX#%##geoY#%#", string1, string2];
NSData* bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
and then you can NSLog(#"Body: %#", bodyString); to see it's contents and then use bodyData for making http request.
body is not an NSString; it is an NSData because of your call to dataUsingEncoding.
I believe this is happening because you are just logging the raw data. Try creating a string from the data and then logging it like this:
body = [[NSString stringWithFormat:#"geoX#%##geoY#%#", string1, string2] dataUsingEncoding:NSUTF8StringEncoding];
NSString *string = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding];
NSLog(#"%#",string);

How to save an array with float values into a text file that is readable by Mac?

I want to save float values stored in an array into a text file and read the file directly on Mac. This is how I create the array:
dataArray = [[NSMutableArray alloc] init];
NSNumber *numObj = [NSNumber numberWithFloat:3.14];
[dataArray insertObject:numObj atIndex:0];
NSNumber *numObj = [NSNumber numberWithFloat:2.3];
[dataArray insertObject:numObj atIndex:1];
...
This is how I save the array:
NSData *savedData = [NSKeyedArchiver archivedDataWithRootObject:dataArray];
NSString *filePath = #"/Users/smith/Desktop/dataArray.txt";
[savedData writeToFile:filePath options:NSDataWritingAtomic error:nil];
When I open the file, the contents are just garbled letters. Instead, I want to make it something like this:
3.14
2.3
1.4
...
the program you've written saves the object representation as an array of NSNumbers, while
the result you want/expect is a text file separated by newlines.
to save those float values into a text file of that format, you could to this:
...
NSMutableString * string = [NSMutableString new];
[string appendFormat:#"%f\n", 3.14];
[string appendFormat:#"%f\n", 2.3];
NSError * error = nil;
BOOL written = [string writeToURL:url atomically:YES encoding:someEncoding error:&error];
...
You can use componentsJoinedByString: to make an in-memory representation first, and then write that representation into a file, like this:
NSString *fileRep = [dataArray componentsJoinedByString:#"\n"];
NSString *filePath = #"/Users/smith/Desktop/dataArray.txt";
[fileRep writeToFile:filePath options:NSDataWritingAtomic error:nil];
This assumes that the number of items is relatively small, because the string representation is created entirely in memory.
Reading back is not as nice as writing out, though: you start by reading back a string, theb split it to components using [fileRep componentsSeparatedByString:#"\n"], and then go through components in a loop or with a block, adding [NSNumber numberWithDouble:[element doubleValue]] for each element of your split.
You probably want to create an XML plist from it to make it human-readable:
[dataArray writeToFile:filePath atomically:YES];
This creates a property list, which is human-readable XML (except if the file already exists AND it's a binary plist, in this case the new plist will also be binary).

Objective-C string arrays

I have a string array as such:
NSArray *names;
names = [NSArray arrayWithObjects:
#"FirstList",
#"SecondList",
#"ThirdList",
nil];
I'm trying to assign an element of this string array to a string variable as such:
NSString *fileName = names[0]; // "Incompatible types in initialization"
or with casting
NSString *fileName = (NSString)names[0]; // "Conversion to non-scalar type requested"
I'm trying to do this, so I can use the string in a method that takes a string as an argument, such as:
NSString *plistPath = [bundle pathForResource:filetName ofType:#"plist"];
Is there no way to assign an element of a string array to a string variable?
Update from 2014: The code in this post actually would work these days since special syntactic support has been added to the framework and compiler for indexing NSArrays like names[0]. But at the time this question was asked, it gave the error mentioned in this question.
You don't use C array notation to access NSArray objects. Use the -objectAtIndex: method for your first example:
NSString *fileName = [names objectAtIndex:0];
The reason for this is that NSArray is not "part of Objective-C". It's just a class provided by Cocoa much like any that you could write, and doesn't get special syntax privileges.
NSArray is a specialized array class unlike C arrays. To reference its contents you send it an objectAtIndex: message:
NSString *fileName = [names objectAtIndex:0];
If you want to perform an explicit cast, you need to cast to an NSString * pointer, not an NSString:
NSString *fileName = (NSString *)[names objectAtIndex:0];
With the new Objective-C literals is possible to use:
NSString *fileName = names[0];
So your code could look like this:
- (void)test5518658
{
NSArray *names = #[
#"FirstList",
#"SecondList",
#"ThirdList"];
NSString *fileName = names[0];
XCTAssertEqual(#"FirstList", fileName, #"Names doesn't match ");
}
Check Object Subscripting for more information.