How to append NSMutable array to existing file

℡╲_俬逩灬. 提交于 2021-02-11 15:44:08

问题


I am newbie in coding and trying to learn objective c, I tried searching my question on internet and stack overflow but not getting proper solution.
I am trying to save some data into array and after that I want to save that subarray into main array and after that main array into file. below code is working properly for me but the data is not appending in file .

self.details = [[NSMutableArray alloc]init];
[self.details insertObject:self.firstName atIndex:0];
[self.details insertObject:self.lastName atIndex:1];
[self.details insertObject:[NSNumber numberWithLong:self.depositAmount] atIndex:2];
[self.details insertObject:[NSNumber numberWithInt:self.accountNumber] atIndex:3];

 for (int i=0; i<self.details.count;i++) {
   NSLog(@"%@",self.details[i]);
 }

 self.mainarray = [[NSMutableArray alloc]init];

 [self.mainarray addObjectsFromArray:self.details];

 NSString *path = @"/Users/testapp/data";

[self.mainarray writeToFile:path atomically:YES];
  enter code here
  for (int i=0; i<self.mainarray.count;i++) {
    NSLog(@"%@",self.mainarray[i]);
 }

回答1:


writeToFile:path is actually deprecated (as you can see here https://developer.apple.com/documentation/foundation/nsdata/1408033-writetofile?language=objc)

In general to do this it depends on what you mean by append? If its literally just dump the data to end ( not necessarily making the file a legit array) then you can open a file in append mode, which you could use an output stream for (https://developer.apple.com/documentation/foundation/nsoutputstream/1564841-outputstreamtofileatpath?language=objc)

However, I am figuring that you want to append the new array objects to the file such that the file is structred. To do that you would need to read in the file and somehow decode that into an array. You would need a way to represent your data such as with JSON (https://developer.apple.com/documentation/foundation/nsjsonserialization) so that you can save the array into the file and vice versa.

But then you would need to read the file, and then add your new structred data so the file would still make sense. There are lots of ways to handle files (NSCoding, C files, etc..) but a simple way would to use NSOutputStream(https://developer.apple.com/documentation/foundation/nsoutputstream) and NSInputStream (https://developer.apple.com/documentation/foundation/nsinputstream?language=objc)



来源:https://stackoverflow.com/questions/61297709/how-to-append-nsmutable-array-to-existing-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!