[NSMutableArray arrayWithContentsOfFile:file]--被赋值为nil后无法用addObject赋值

出现的问题以及对应的解决办法

—问题

这时的filepath只不过是一个空文件(我将存好数据的collectArray数组加到dataArray数组里面,再重新写进filepath文件)

NSMutableArray *dataArray = [NSMutableArray arrayWithContentsOfFile:filepath];

在这里插入图片描述
运行的结果是:
在这里插入图片描述
会发现尽管往里面加了数据,但数组始终还是nil的状态(那就是还没有初始化)

出现这种现象的原因–

Return Value
A mutable 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 a mutable array. The returned object must be different than the original receiver.

initWithContentsOfFile:苹果文档

重点就是if the file can’t be opened or the contents of the file can’t be parsed into a mutable array如果不能被打开或者解析为一个可变数组的时候,就返回nil。

看来对于nil调用addObject的方式,依然结果会是nil。

也就是说本身的数组为nil时,加数组还是nil

解决办法–

方法1:

先判断文件是否为空,然后对数组进行初始化,这样再往里面addObject时不会再显示nil状态了

if ([NSMutableArray arrayWithContentsOfFile:filepath]==nil) {
        NSArray *kArr = [NSArray array];
        BOOL ret = [kArr writeToFile:filepath atomically:YES];
        if (ret) {
            //获取collect.plist文件里面原有的数据
            dataArray = [NSMutableArray arrayWithContentsOfFile:filepath];
        }
        else
        {
            NSLog(@"创建collect.plist失败了");
        }
        
    }
    else{
        //获取collect.plist文件里面原有的数据
        dataArray = [NSMutableArray arrayWithContentsOfFile:filepath];
    }

方法二

先把文件赋值给数组,再判断数组是否为nil状态

NSMutableArray *dataArray = [NSMutableArray arrayWithContentsOfFile:filepath];
    if(!dataArray){
        dataArray = [NSMutableArray new];
    }
发布了11 篇原创文章 · 获赞 11 · 访问量 889

猜你喜欢

转载自blog.csdn.net/kk177/article/details/105716380