- 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 - Foundation框架
- 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
广告