将 NSMutableArray 或 NSMutableDictionary 传递给方法 - 您可以添加到其中吗?
如果我有一个 NSMutableArray
或 NSMutableDictionary
并将其传递给一个方法 la:
-(void)addToThisArray:(NSMutableArray *)theMutableArray
{
[theMutableArray addObject:@"test"];
}
并像这样调用它:
NSMutableArray *theMutableArrayToPass = [[NSMutableArray alloc] init];
[theMutableArrayToPass addObject:@"2"];
[self addToThisArray:theMutableArrayToPass];
这是更改 NSMutableArray
的有效方法吗> 或 NSMutableDictionary
?当然,我会对数组/字典做的事情比这个例子多得多,但我习惯了 Perl,而且我们一直通过引用传递。
If I have an NSMutableArray
or NSMutableDictionary
and pass it to a method a la:
-(void)addToThisArray:(NSMutableArray *)theMutableArray
{
[theMutableArray addObject:@"test"];
}
and call it like:
NSMutableArray *theMutableArrayToPass = [[NSMutableArray alloc] init];
[theMutableArrayToPass addObject:@"2"];
[self addToThisArray:theMutableArrayToPass];
Is this a valid way to alter an NSMutableArray
or NSMutableDictionary
? I, of course, would do much more to the array/dictionary than this example, but I am used to Perl, and we pass by reference all the time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,objective-c 也总是通过对象的引用传递。
自从写了这个答案以来,现在有一个例外,尽管它是一个实现细节,并且不会改变声明的实际细节。
标记指针技术上是按值传递的,因为引用实际上是数据。根据定义,它们也是不可变的,这就是为什么这是一个没有实际影响的实现细节。
Yes, objective-c is also always pass by reference for objects.
Since this answer was written, there is now an exception though it is an implementation detail and doesn't change the practical details of the claim.
Tagged pointers are technically pass by value because the reference is really the data. They are also, by definition, immutable which is why this is an implementation detail that has not practical ramifications.