可以使用 NSMutableData 对象调用 +[NSData dataWithData:] 吗?
我执行以下操作将可变数据实例更改为不可变是否有问题?
NSMutableData *mutData = [[NSMutableData alloc] init];
//Giving some value to mutData
NSData *immutableData = [NSData dataWithData:mutData];
[mutData release];
Is it a problem for me to do the following to change a mutable data instance immutable?
NSMutableData *mutData = [[NSMutableData alloc] init];
//Giving some value to mutData
NSData *immutableData = [NSData dataWithData:mutData];
[mutData release];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这完全没问题,实际上是 dataWithData: 的主要用途之一——创建可变对象的不可变副本。*
NSData
也符合 < a href="http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSCopying_Protocol/" rel="noreferrer">NSCopying
协议,**这意味着您可以改用[mutData copy]
。不同之处在于dataWithData:
返回一个不属于您的对象(它是自动释放的),而 每个内存管理规则,copy
创建一个由您负责其内存的对象。dataWithData:
与[[mutData copy] autorelease]
效果相同。因此,您可以选择
dataWithData:
或copy
,具体取决于您对结果对象生命周期的要求。*这也适用于具有可变子类的其他类中的类似方法,例如,
+[NSArray arrayWithArray:]
。**另请参阅“对象复制” 在核心能力指南中。
This is completely okay, and is in fact one of the primary uses of
dataWithData:
-- to create an immutable copy of a mutable object.*NSData
also conforms to theNSCopying
protocol,** which means you could instead use[mutData copy]
. The difference is thatdataWithData:
returns an object you do not own (it is autoreleased), whereas per memory management rules,copy
creates an object for whose memory you are responsible.dataWithData:
is equivalent in effect to[[mutData copy] autorelease]
.So you can choose either
dataWithData:
orcopy
, dependent upon your requirements for the lifetime of the resulting object.*This also applies to similar methods in other classes which have a mutable subclass, e.g.,
+[NSArray arrayWithArray:]
.**See also "Object Copying" in the Core Competencies Guide.
不,这不是问题。
immutableData
将使用mutData
中的数据进行初始化。No it is not a problem.
immutableData
will be initialized with the data inmutData
.