- 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 中的引用调用
引用传递方法是将参数传递给函数,它会将参数的地址复制到形式参数中。在函数内部,该地址用于访问调用中使用的实际参数。这意味着对参数所做的更改会影响传递的参数。
要按引用传递值,需要像传递任何其他值一样将参数指针传递给函数。因此,您需要像以下函数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;
}
要查看有关 Objective-C - 指针的更多详细信息,您可以查看Objective-C - 指针章节。
现在,让我们通过按引用传递值来调用函数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 */
return;
}
@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:27:17.716 demo[6721] Before swap, value of a : 100 2013-09-09 12:27:17.716 demo[6721] Before swap, value of b : 200 2013-09-09 12:27:17.716 demo[6721] After swap, value of a : 200 2013-09-09 12:27:17.716 demo[6721] After swap, value of b : 100
这表明更改也反映在函数外部,这与值传递不同,值传递中的更改不会反映在函数外部。
objective_c_functions.htm
广告