0

I have a NSString that I can decide the format for, in which I will store contact groups and group members, like so:

Friends|John Smith|Jane Doe
Imaginary Friends|Mary Poppins|Harry Potter|Arya Stark
(\n after last member name)

The "|" is a temporary divider I'm using because it is unlikely to appear in contact and group names.

I save this to file and need to extract the groups and group members names as NSStrings when I next load up this file. How would I do this?

2
  • First, you might want to store your names in an array so you can sort them, etc. You can always add the comma, |, or whatever when you write to file, but your life will be easier without them while trying to do sort or other operations. Second, consider using an existing file format. For example, there are good JSON libraries, and you can store an array right to JSON and then pull it back into your program as an array. Commented Jan 6, 2012 at 3:24
  • 1
    Why not just write an array to and from a file? See stackoverflow.com/questions/1487606/saving-a-nsarray Commented Jan 6, 2012 at 3:31

2 Answers 2

2

I think you want to look at NSString method - (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator or - (NSArray *)componentsSeparatedByString:(NSString *)separator

e.g.

NSArray* members = [contactLine componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: @"|"]];
Sign up to request clarification or add additional context in comments.

1 Comment

This is the way I ended up doing it, but now to think about it, I don't think parsing strings was the right way to save the information. Thanks anyways for the rapid answer.
1

You should reconsider creating your own file format with your own custom delimiters etc...

You could write an array to and from a file using:

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
- (id)initWithContentsOfFile:(NSString *)aPath    

If you are storing custom objects, you could also implement NSCoding and NSKeyedArchiver

See Saving a NSArray

Finally, you could use CoreData or Sqlite if you data and querying patterns become more complex.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.