Array(数组)
视频锁定
{$ currentTime | date:'mm:ss' $}
{$ timeLeft | date:'mm:ss' $}
上节课,我们学习了字符串的类NSString
,它是用来存放文本类型的;
还有一些其他的类,用来存放不同的数据类型;
NSNumber
,它是用来存放数字的;
NSDate
,它是用来存放日期的;
大家看出来了,在Objective-C中,有很多类是以NS开头的,这些类都存放在FoundationFramework
这个框架中,框架好比容器,里面有各种各样我们需要的类。
下面,我们就用这些类来继续完善我们的水晶球应用。
我们来添加一个预测结果的列表,并且,这个结果是随机产生的。这个列表,我们就用NSArray
(数组类)这个类来实现,数组是一个比较特殊的数据类型,在数组里面,可以存放多个数据对象,并且这些对象都有它自己的位置,这个位置我们称作索引(Index
)。
让我们来创建一个颜色数组,并按照顺序放入数组中。
注意,数组的索引从0开始,我们访问数组中的具体对象,就要用objectAtIndex
这个方法,并将要访问的对象的索引位置当作参数传递给objectAtIndex
,下面我们看看如何来创建一个数组。
我们点击ViewController.m
这个文件,找到buttonPressed
这个方法,在该方法里面,我们输入如下代码:
NSArray *predictionArray = [[NSArray alloc] initWithObjects:@"it is certain",
@"it is decidely so",
@"All signs say YES",
@"The stars are not aligned",
@"My reply is no",
@"It is doubtful",
@"Better not tell you now",
@"Concentrate and ak again",
@"Unable to anwser now", nil];
NSString *predictionArrayZero=[predictionArray objectAtIndex:0];
NSString *preditionArrayFive=[predictionArray objectAtIndex:4];
NSString *preditionArrayNine=[predictionArray objectAtIndex:8]; NSLog(@"predictionArrayZero = %@",predictionArrayZero);
NSLog(@"preditionArrayFive = %@",preditionArrayFive);
NSLog(@"preditionArrayNine = %@",preditionArrayNine);
predictionLabel.text = [predictionArray objectAtIndex:0];
具体该每条语句的意思,请跟着Lucy老师一起去学吧…
在线练习
{$ activeFileHint $}