17

I am trying to read an input file (if it exists) and then want to add a string to that input. My code looks as follows.

NSMutableArray *listData = [[NSMutableArray alloc] initWithContentsOfFile:*filepath*];
// listData = null if the input file does not exist.
NSString *jobName = [NSString stringWithFormat:@"My New Job"];
[listData addObject:jobName];

if the input exists then after addObject:jobName, the listData is updated but if the input file does not exist the listData still gives null after addObject:jobName. My input file (if exists) looks something like.

<array>
      <string>My Job 1</string>
      <string>My Job 2</string>
      <string>My Job 3</string>
</array>

I want to add the string in the existing array of strings or want to create a new array of string jobName if it is not already there. Can somebody help me out. Which method I should use to create a new array of string when the input file does not exist.

3 Answers 3

36

One of some possibilities:

if (!listData) listData = [[NSMutableArray alloc] init];
[listData addObject:jobName];
Sign up to request clarification or add additional context in comments.

Comments

5

From the documentation:

- (id)initWithContentsOfFile:(NSString *)aPath

An array initialized to contain the contents of the file specified by aPath or nil if the file can’t be opened or the contents of the file can’t be parsed into an array. The returned object might be different than the original receiver.

So if the file doesn't exist, you'll have to create the array manually using:

listData = [[NSMutableArray alloc] init];

1 Comment

Thank you very much Dave DeLong. It helped me.
5

You Can Add Object in NSMutableArray using two methods

  1. addObject
  2. insertObject:atIndex

1.using addObject

[myMutableArray addObject:myObject];

2.using inserObject:atIndex

[myMutableArray insertObject:myObject atIndex:index];

Note: Index value must be valid(Within Range)

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.