Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add object to NSMutableArray

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.

like image 597
UCU110 Avatar asked Aug 13 '10 20:08

UCU110


People also ask

How to add objects in NSMutableArray?

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];

What is NSMutableArray Objective C?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

Is NSMutableArray thread safe?

In general, the collection classes (for example, NSMutableArray , NSMutableDictionary ) are not thread-safe when mutations are concerned. That is, if one or more threads are changing the same array, problems can occur.


1 Answers

One of some possibilities:

if (!listData) listData = [[NSMutableArray alloc] init];
[listData addObject:jobName];
like image 152
Georg Fritzsche Avatar answered Oct 24 '22 14:10

Georg Fritzsche