Reading strings from txt files into NSArrays in iOS - objective-c

After much reading it seems that, really, the only way to read a number of lines from a text file into an NSArray is with this:
NSString *myfilePath = [[NSBundle mainBundle] pathForResource:#"poem" ofType:#"txt"];
NSString *linesFromFile = [[NSString alloc] initWithContentsOfFile:myfilePath encoding:NSUTF8StringEncoding error:nil];
myArrayOfLines = [NSArray alloc];
myArrayOfLines = [linesFromFile componentsSeparatedByString:#"\n"];
NSArrays have a method for initWithContentsOfFile but I have not seen any examples of how to use this. I have read some posts that state that the file must be a plist and not a generic txt file.
Is this really the case? Is there a way to read lines (terminated with \n) directly into an NSArray?

You have it right, except the line myArrayOfLines = [NSArray alloc]; which is useless.
Don't bother with plist if you already have a good txt file.
But for curiosity, here is a link which explains how it works with plist files : link
Also, if you don't use ARC, you'll have some leaks, but that's another question, and we don't have the whole code, so I might be wrong.

Related

plist wont pull into my NSMutableArray. am i missing something?

So here's my code. I'm trying to display content from a plist into a table and i keep running into errors. ive been at it all day so i'm probably missing something fairly easy. hope you guys can figure out why when i build, the table is empty.
here is my plist (without headers):
<array>
<dict>
<key>word</key>
<string>AWord1</string>
<key>definition</key>
<string>here is a definition</string>
<key>partOfSpeech</key>
<string>here is a part of speech</string>
</dict>
<dict>
<key>word</key>
<string>Bword1</string>
<key>definition</key>
<string>here is a definition</string>
<key>partOfSpeech</key>
<string>here is a part of speech</string>
</dict>
</array>
</plist>
edit: closing tags were missing due to misformatting - fixed
ok. here is my new code. i NSLog'd and decided to back up to before i went to plist. so, if you could help. how would you suggest i pull this data from plist instead (assuming the data is in the plist)
//Initialize the array.
listOfItems = [[NSMutableArray alloc] init];
NSArray *countriesToLiveInArray = [NSArray arrayWithObjects:#"Iceland", #"Greenland", #"Switzerland", #"Norway", #"New Zealand", #"Greece", #"Italy", #"Ireland", nil];
NSDictionary *countriesToLiveInDict = [NSDictionary dictionaryWithObject:countriesToLiveInArray forKey:#"Countries"];
NSArray *countriesLivedInArray = [NSArray arrayWithObjects:#"India", #"U.S.A", #"Test", #"Test", #"Test", #"Test", #"Test", #"Test", #"Test", #"Test", #"Test", #"Test", #"Test", #"Test", #"Test", #"Test", nil];
NSDictionary *countriesLivedInDict = [NSDictionary dictionaryWithObject:countriesLivedInArray forKey:#"Countries"];
[listOfItems addObject:countriesToLiveInDict];
[listOfItems addObject:countriesLivedInDict];
//Initialize the copy array.
copyListOfItems = [[NSMutableArray alloc] init];
//Set the title
self.navigationItem.title = #"Countries";
//Add the search bar
self.tableView.tableHeaderView = searchBar;
searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
searching = NO;
letUserSelectRow = YES;
i feel as though i'm still not actually telling it to parse the data from the plist. i've only init'd it. thoughts?
Your code seems very incomplete, it doesn't bear much relation to the plist. Here are a few issues
as noted by H2CO3 and Fogmeister, the plist as you show it is missing a closing </array> tag (but lets assume that is a typo in the question)
you load the entire array into a single entry in a countriesToLiveIn dictionary (against the key "definition")
countriesToLiveIn becomes a single object in the array listOfItems
you initialise a copyOfListItems array but then don't do anything with it
Then you do not indicate where the table is getting it's date from.
If it is from copyOfListItems, well that array is empty .: empty table.
If it is from listOfItems you will be parsing the countriesToLiveIn dictionary somehow, but you don't show how.
If it is directly from the plist array countriesToLiveInArray then that missing </array> tag could be a clue. You would also need to be parsing the array's contained dictionaries somehow, and you don't show us that code, there could be something wrong there.
To get further with this I suggest copious use of NSLog to find out how far the data gets in to your objects. Perhaps you could expand your question with the results if you are still getting stuck.
update
Following your updated code, my first suspicion is that there was a problem with your URL.
in your previous edit this is the suspect line
NSMutableArray *wordListArray = [[NSMutableArray alloc] initWithContentsOfURL: [NSURL URLWithString:#"http://url.com/dictpPlist.plist"]];
You need to NSLog right after it:
NSLog (#"wordListArray %#", wordListArray);
To confirm that you are not picking up the plist here. At least then we isolate the problem to this point in your code.
Then we need to question the URL - is it correct? how did the plist get there? can you verify it independently? Is it a local file URL or a network URL?
If you are accessing a network resource, this is quite likely your problem. The initWithContentsOfURL methods should only really be used with local filesystem URLs. See for example
initwithcontentsofurl methods considered harmful.
You should be using NSURLConnection asynchronously instead. Apple is a little cagey about this also:
aURL: The location of a file containing a string representation of an array produced by the writeToURL:atomically: method.
Assuming this is your issue, why don't you get it working with a local filesystem plist first.
Write one in code from your listOfItems array:
- (void) createPlist
{
NSFileManager* fManager = [NSFileManager defaultManager];
NSError* error;
NSURL* docsURL = [fManager URLForDirectory:NSDocumentDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create:NO
error:&error];
NSURL* plistURL = [docsURL URLByAppendingPathComponent:#"testlist.plist"];
[listOfItems writeToURL:plistURL atomically:YES];
}
Read it back in, verify it works, then sort out how to do the same over a network.
try below code
// Path to the plist (in the application bundle)
NSString *path = [[NSBundle mainBundle] pathForResource:
#"dictpPlist" ofType:#"plist"];
// Build the array from the plist
NSMutableArray *array2 = [[NSMutableArray alloc] initWithContentsOfFile:path];
// Show the string values
for (NSString *str in array2)
NSLog(#"--%#", str);

NSString WriteToFile not stay permanent?

I am trying to save text stored in an NSString variable in a text file that is stored with the main bundle of my project.
So far I have had no success and tried a lot of different methods.
Why doesn't this stay permanent?
NSString *pathToFile = [[NSString alloc]init];
pathToFile = [[NSBundle mainBundle] pathForResource:#"ListOfSavedImages" ofType:#"txt"];
NSLog(#"%#",pathToFile);
NSString *stringToWriteToFile = [[NSString alloc]init];
stringToWriteToFile=#"Adam";
NSLog(#"%#",stringToWriteToFile);
[stringToWriteToFile writeToFile:pathToFile atomically:YES encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"called!");
NSString *contentsOfFile1 = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"%#",contentsOfFile1);
The actual file doesn't change although the NSLog at the end of this code segment outputs "Adam" but I am also nslogging the contents of the file when the view loads and it always reverts back to the original text(it never actually changes). What am I doing wrong?
I am using Xcode 4.3, ARC, and storyboards.
As you are instantiating your variables locally, they will leak away when you hit the end of the block }.
Try using IVars declared as properties of the particular view controller, synthesized in the .m file.
Look at the C139p at Stanford Course on ITunes, preferably the earlier series given before ARC as this fully explains the concept of data persistence.

Weird problem with NSString initWithContentsOfFile

I have a .csv file in my bundle which I need to parse into an NSArray. The problem is when I init an NSString with contents of file (the file is located in my bundle), it returns nil. However, if I change the contents of the file, to anything else (random), it works. Is it possible there's some sort of string/character in the file that might be messing with the initialization?
It's just a simple csv file with 2 columns, a number, a comma, some text and "\n".
Thanks.
CSV => NSArray?
https://github.com/davedelong/CHCSVParser
*disclaimer: I wrote it.
Works for me:
NSStringEncoding usedEncoding = 0;
NSError *csvError = nil;
NSString *raw = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://pastebin.com/raw.php?i=RXPPwpvy"] usedEncoding:&usedEncoding error:&csvError];
NSLog(#"raw: %#", raw);
NSLog(#"%#", [NSArray arrayWithContentsOfCSVString:raw encoding:usedEncoding error:&csvError]);

How can I read the iTunesMetadata.plist in Objective-C? (ipa file is on disk)

Ok I can get the list of IPA files in my iTunes folder. what I want to do is be able to read the plist file in the IPA file.
I'm very new to Objective-C so sorry if this is an obvious question (I did look).
I tried the following but it comes back null.
// i = NSURL. value eg. "file://localhost/Users/jiyeon/Desktop/test/test.ipa"
NSDictionary *plistInfo = [NSDictionary dictionaryWithContentsOfFile:[[i absoluteString]
stringByAppendingPathComponent:#"iTunesMetadata.plist"]];
However plistInfo just ends up being null.
Try -(NSString *)path NSURL
NSDictionary *plistInfo = [NSDictionary dictionaryWithContentsOfFile:[[i path]
stringByAppendingPathComponent:#"iTunesMetadata.plist"]];
this should work

best way to get text from a plain .txt file into a Scroll View

Can someone please help me out with this I'm actually going nuts!
What is the best way to get text from a plain .txt file into a Scroll View, thats all I need just text.
I've tried so many different solutions but can't get any of them working I was hoping someone could give me a fresh overview.
Is the file a resource in your application or are you loading it from a network resource? If embedded, you can load it into an NSString object and then set the text property of the UITextView with that. Something like:
UITextView *myTextView = [[UITextView alloc] init];
NSString *pathToFile = [[NSBundle mainBundle] pathForResource:#"yourTextFile" ofType:#"txt"];
NSString *theText = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:nil];
myTextView.text = theText;