- 基本 Objective-C
- Objective-C - 主页
- Objective-C - 概述
- Objective-C - 环境设置
- Objective-C - 程序结构
- Objective-C - 基本语法
- Objective-C - 数据类型
- Objective-C - 变量
- Objective-C - 常量
- Objective-C - 运算符
- Objective-C - 循环
- Objective-C - 决策
- Objective-C - 函数
- Objective-C - 块
- Objective-C - 数字
- Objective-C - 数组
- Objective-C - 指针
- Objective-C - 字符串
- Objective-C - 结构
- Objective-C - 预处理器
- Objective-C - Typedef
- Objective-C - 类型转换
- Objective-C - 日志处理
- Objective-C - 错误处理
- 命令行参数
- 高级 Objective-C
- Objective-C - 类和对象
- Objective-C - 继承
- Objective-C - 多态性
- Objective-C - 数据封装
- Objective-C - 类别
- Objective-C - 摆姿势
- Objective-C - 扩展
- Objective-C - 协议
- Objective-C - 动态绑定
- Objective-C - 复合对象
- Obj-C - 基础框架
- Objective-C - 快速枚举
- Obj-C - 内存管理
- Objective-C 有用资源
- Objective-C - 快速指南
- Objective-C - 有用的资源
- Objective-C - 讨论
Objective-C 中按值调用函数
将参数传递给函数的按值调用方法将参数的实际值复制到函数的形式参数中。在这种情况下,对函数内部参数所做的更改不会对参数产生影响。
默认情况下,Objective-C 编程语言使用按值调用方法来传递参数。一般来说,这意味着函数内的代码无法更改用于调用该函数的参数。考虑函数swap()定义如下 -
/* function definition to swap the values */
- (void)swap:(int)num1 andNum2:(int)num2 {
int temp;
temp = num1; /* save the value of num1 */
num1 = num2; /* put num2 into num1 */
num2 = temp; /* put temp into num2 */
return;
}
现在,让我们通过传递实际值来调用函数swap(),如下例所示 -
#import <Foundation/Foundation.h>
@interface SampleClass:NSObject
/* method declaration */
- (void)swap:(int)num1 andNum2:(int)num2;
@end
@implementation SampleClass
- (void)swap:(int)num1 andNum2:(int)num2 {
int temp;
temp = num1; /* save the value of num1 */
num1 = num2; /* put num2 into num1 */
num2 = temp; /* put temp into num2 */
}
@end
int main () {
/* local variable definition */
int a = 100;
int b = 200;
SampleClass *sampleClass = [[SampleClass alloc]init];
NSLog(@"Before swap, value of a : %d\n", a );
NSLog(@"Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
[sampleClass swap:a andNum2:b];
NSLog(@"After swap, value of a : %d\n", a );
NSLog(@"After swap, value of b : %d\n", b );
return 0;
}
让我们编译并执行它,它将产生以下结果 -
2013-09-09 12:12:42.011 demo[13488] Before swap, value of a : 100 2013-09-09 12:12:42.011 demo[13488] Before swap, value of b : 200 2013-09-09 12:12:42.011 demo[13488] After swap, value of a : 100 2013-09-09 12:12:42.011 demo[13488] After swap, value of b : 200
这表明尽管函数内部的值发生了更改,但值没有发生变化。
Objective_c_functions.htm