- 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 编程语言不允许将整个数组作为函数参数返回。但是,您可以通过指定数组名称(不带索引)来返回指向数组的指针。您将在下一章学习指针,因此您可以跳过本章,直到您理解 Objective-C 中指针的概念。
如果要从函数返回一维数组,则必须声明一个返回指针的函数,如下例所示:
int * myFunction() {
.
.
.
}
第二个需要记住的是,Objective-C 不建议将局部变量的地址返回到函数外部,因此您必须将局部变量定义为**静态**变量。
现在,考虑以下函数,它将生成 10 个随机数并使用数组返回它们,并按如下方式调用此函数:
#import <Foundation/Foundation.h>
@interface SampleClass:NSObject
- (int *) getRandom;
@end
@implementation SampleClass
/* function to generate and return random numbers */
- (int *) getRandom {
static int r[10];
int i;
/* set the seed */
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i) {
r[i] = rand();
NSLog( @"r[%d] = %d\n", i, r[i]);
}
return r;
}
@end
/* main function to call above defined function */
int main () {
/* a pointer to an int */
int *p;
int i;
SampleClass *sampleClass = [[SampleClass alloc]init];
p = [sampleClass getRandom];
for ( i = 0; i < 10; i++ ) {
NSLog( @"*(p + %d) : %d\n", i, *(p + i));
}
return 0;
}
编译并执行上述代码后,将产生如下结果:
2013-09-14 03:22:46.042 demo[5174] r[0] = 1484144440 2013-09-14 03:22:46.043 demo[5174] r[1] = 1477977650 2013-09-14 03:22:46.043 demo[5174] r[2] = 582339137 2013-09-14 03:22:46.043 demo[5174] r[3] = 1949162477 2013-09-14 03:22:46.043 demo[5174] r[4] = 182130657 2013-09-14 03:22:46.043 demo[5174] r[5] = 1969764839 2013-09-14 03:22:46.043 demo[5174] r[6] = 105257148 2013-09-14 03:22:46.043 demo[5174] r[7] = 2047958726 2013-09-14 03:22:46.043 demo[5174] r[8] = 1728142015 2013-09-14 03:22:46.043 demo[5174] r[9] = 1802605257 2013-09-14 03:22:46.043 demo[5174] *(p + 0) : 1484144440 2013-09-14 03:22:46.043 demo[5174] *(p + 1) : 1477977650 2013-09-14 03:22:46.043 demo[5174] *(p + 2) : 582339137 2013-09-14 03:22:46.043 demo[5174] *(p + 3) : 1949162477 2013-09-14 03:22:46.043 demo[5174] *(p + 4) : 182130657 2013-09-14 03:22:46.043 demo[5174] *(p + 5) : 1969764839 2013-09-14 03:22:46.043 demo[5174] *(p + 6) : 105257148 2013-09-14 03:22:46.043 demo[5174] *(p + 7) : 2047958726 2013-09-14 03:22:46.043 demo[5174] *(p + 8) : 1728142015 2013-09-14 03:22:46.043 demo[5174] *(p + 9) : 1802605257
objective_c_arrays.htm
广告