标题: Foundation框架之不可变数组 [打印本页] 作者: mac 时间: 2015-9-23 10:12 标题: Foundation框架之不可变数组 //
// main.m
// FoundationFramework
//
// Created by Kenshin Cui on 14-2-16.
// Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//
Person *person1=[Person personWithName:@"Kenshin"];
Person *person2=[Person personWithName:@"Kaoru"];
Person *person3=[Person personWithName:@"Rosa"];
NSArray *array2=[[NSArray alloc]initWithObjects:person1,person2,person3, nil];
[array2 makeObjectsPerformSelector:@selector(showMessage:) withObject:@"Hello,world!"];//执行所有元素的showMessage方法,后面的参数最多只能有一个
/*结果:
My name is Kenshin,the infomation is "Hello,world!".
My name is Kaoru,the infomation is "Hello,world!".
My name is Rosa,the infomation is "Hello,world!".
*/
}
//数组的遍历
void test2(){
NSObject *obj=[[NSObject alloc]init];
NSArray *array=[[NSArray alloc] initWithObjects:@"abc",obj,@"cde",@"opq",@25, nil];
//方法1
for(int i=0,len=array.count;i<len;++i){
NSLog(@"method1:index %i is %@",i,[array objectAtIndex:i]);
}
/*结果:
method1:index 0 is abc
method1:index 1 is <NSObject: 0x100106de0>
method1:index 2 is cde
method1:index 3 is opq
method1:index 4 is 25
*/
//方法2
for(id obj in array){
NSLog(@"method2:index %zi is %@",[array indexOfObject:obj],obj);
}
/*结果:
method2:index 0 is abc
method2:index 1 is <NSObject: 0x100602f00>
method2:index 2 is cde
method2:index 3 is opq
method2:index 4 is 25
*/
//方法3,利用代码块方法
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"method3:index %zi is %@",idx,obj);
if(idx==2){//当idx=2时设置*stop为YES停止遍历
*stop=YES;
}
}];
/*结果:
method3:index 0 is abc
method3:index 1 is <NSObject: 0x100106de0>
method3:index 2 is cde
*/