- 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 - 块 (Blocks)
- 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 - 分类 (Categories)
- Objective-C - 模拟 (Posing)
- Objective-C - 扩展 (Extensions)
- Objective-C - 协议 (Protocols)
- Objective-C - 动态绑定
- Objective-C - 组合对象
- Obj-C - Foundation框架
- Objective-C - 快速枚举
- Obj-C - 内存管理
- Objective-C有用资源
- Objective-C - 快速指南
- Objective-C - 有用资源
- Objective-C - 讨论
在Objective-C中传递指针给函数
Objective-C编程语言允许您将指针传递给函数。为此,只需将函数参数声明为指针类型即可。
以下是一个简单的示例,我们将一个无符号长整型指针传递给一个函数,并在函数内部更改其值,该值会反映回调用函数中:
#import <Foundation/Foundation.h>
@interface SampleClass:NSObject
- (void) getSeconds:(int *)par;
@end
@implementation SampleClass
- (void) getSeconds:(int *)par {
/* get the current number of seconds */
*par = time( NULL );
return;
}
@end
int main () {
int sec;
SampleClass *sampleClass = [[SampleClass alloc]init];
[sampleClass getSeconds:&sec];
/* print the actual value */
NSLog(@"Number of seconds: %d\n", sec );
return 0;
}
编译并执行上述代码后,将产生以下结果:
2013-09-13 23:50:47.572 demo[319] Number of seconds: 1379141447
可以接受指针的函数也可以接受数组,如下例所示:
#import <Foundation/Foundation.h>
@interface SampleClass:NSObject
/* function declaration */
- (double) getAverage:(int *)arr ofSize:(int) size;
@end
@implementation SampleClass
- (double) getAverage:(int *)arr ofSize:(int) size {
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = (double)sum / size;
return avg;
}
@end
int main () {
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
SampleClass *sampleClass = [[SampleClass alloc]init];
/* pass pointer to the array as an argument */
avg = [sampleClass getAverage: balance ofSize: 5 ] ;
/* output the returned value */
NSLog(@"Average value is: %f\n", avg );
return 0;
}
编译并执行上述代码后,将产生以下结果:
2013-09-14 00:02:21.910 demo[9641] Average value is: 214.400000
objective_c_pointers.htm
广告