将空 NSArray 保存到磁盘
我有一个 NSMutableArray。它可以是空的,也可以有多个 propertyList 对象(在我的例子中只有 NSNumber 对象)。 我想以xml格式将其保存到磁盘,所以我使用。
// In the interface
@property (nonatomic, retain) NSMutableArray *myArray;
// In the implementation
if ([self.myArray writeToFile:pathToFile atomically:YES])
{
// Success
} else {
// Failure
}
如果调用该方法时数组为空(一个空的初始化 NSMutableArray),该方法将返回 NO 并且操作未完成,因此旧数据不会被覆盖。
如何将空数组写入磁盘?
I have a NSMutableArray. It can be empty or have a number of propertyList objects (In my case just NSNumber objects).
I want to save it to disk in xml format, so I'm using.
// In the interface
@property (nonatomic, retain) NSMutableArray *myArray;
// In the implementation
if ([self.myArray writeToFile:pathToFile atomically:YES])
{
// Success
} else {
// Failure
}
If the array is empty ( an empty initialized NSMutableArray) in the moment the method is called the method returns NO and the operation is not done, so the old data is not overwritten.
How can I write an empty array to disk?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您确定 self.myArray 实际上是一个“空的初始化 NSMutableArray”吗?对我来说,告诉一个空数组将其自身写入文件效果很好。
您观察到的行为,即消息返回
NO
,与self.myArray
返回nil
一致,这意味着它既不是空的,也不是非空,因为你根本没有数组。如果没有数组,则没有任何可发送消息的对象,因此消息返回(在本例中)NO
。在您尝试向其发送消息时,绝对确保 self.myArray 实际上返回一个数组,无论是空数组还是其他数组。您用来验证的日志代码和输出对于您来说将是一件很棒的事情,可以添加到您的问题中。
Are you sure
self.myArray
is in fact an “empty initialized NSMutableArray”? For me, telling an empty array to write itself to a file works fine.The behavior you're observing, that the message returns
NO
, is consistent withself.myArray
returningnil
, which means it is neither empty nor non-empty, because you don't have an array at all. With no array, there is nothing to send a message to, so the message returns (in this case)NO
.Make absolutely sure that
self.myArray
is in fact returning an array, empty or otherwise, at the point where you're trying to send it a message. The logging code and output you used to verify that would be a great thing for you to add to your question.