如何将对象添加到NSMutableArray [英] 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];
如果输入存在,则在 addObject:jobName 之后, listData 已更新,但如果输入文件不存在, listData 在 addObject:jobName 之后仍为null。我的输入文件(如果存在)看起来像。
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>
我想在现有的字符串数组中添加字符串,或者想要创建一个新的字符串数组jobName,如果它还没有。有人可以帮助我吗?当输入文件不存在时,我应该使用哪种方法创建一个新的字符串数组。
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.
推荐答案
一些可能性:
if (!listData) listData = [[NSMutableArray alloc] init];
[listData addObject:jobName];
这篇关于如何将对象添加到NSMutableArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!