NSMutableArray 不应该保留添加的对象吗?
您好,我遇到了 Linux/GNUstep 的问题。我的 NSMutableArray 似乎没有保留任何添加的对象。他们不应该吗?示例:
NSString * str = @"test";
NSMutableArray * arr = [[NSMutableArray alloc] init];
NSLog(@"before add retainCount: %d", [str retainCount]);
[arr addObject: str];
NSLog(@"after add retainCount: %d", [str retainCount]);
输出:
before add retainCount: 1
after add retainCount: 1
Hi I am facing an issue with Linux / GNUstep. My NSMutableArray(s) do not seem to retain any added objects to them. Shouldn't they? Example:
NSString * str = @"test";
NSMutableArray * arr = [[NSMutableArray alloc] init];
NSLog(@"before add retainCount: %d", [str retainCount]);
[arr addObject: str];
NSLog(@"after add retainCount: %d", [str retainCount]);
Output:
before add retainCount: 1
after add retainCount: 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
(第一:您永远不应该依赖
-retainCount
。)在幕后,常量字符串(定义为
@"foo"
的字符串)的特殊之处在于-retain
和-release
实际上并没有做任何事情;作为优化,它们始终将保留计数设置为 1。如果您执行以下操作:
您可能会看到您所期望的结果。
(First: You should never rely on
-retainCount
.)Under the hood, constant strings (strings defined as, e.g.,
@"foo"
) are special in that-retain
and-release
don't actually do anything; they're always around with a retain count of 1 as an optimization.If you do something like:
You may see what you expect.