您的位置:首页 > 其它

OC中NSArray

2016-01-07 11:26 218 查看
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
@autoreleasepool {
/**
*  NSArray 数组,可以存储任何类型的OC对象
NSEnumerator,
NSDictionary 字典,键值对
NSSet 数学的集合
*/

//1.如何创建一个NSArray,即初始化
NSArray *names=[NSArray arrayWithObjects:@"张三",@"李四",@"王五", nil];
// NSLog(@"%@",names);

//        NSInteger a=[names count];
//2.集合元素的个数
//        NSLog(@"元素的个数是=%ld",a);

//3.获取集合的指定下标的元素
//        NSString *name=[names objectAtIndex:1];
//        NSLog(@"%@",name);

//4.循环遍历
//        for (int i=0; i<[names count]; i++) {
//        NSString *name=[names objectAtIndex:i];
//        NSLog(@"%@",name);
//        }

//        for (int i=0; i<[names count]; i++) {
//            NSLog(@"%@",names[i]);
//        }
// 快速枚举
//        for (NSString *name in names) {
//            NSLog(@"%@",name);
//        }

}
return 0;
}


把对象变成NSArray输出

#import <Foundation/Foundation.h>

@interface Student : NSObject
/**
*  属性,姓名,年龄
*/
@property(strong,nonatomic) NSString *name;
@property(assign,nonatomic) int age;
-(instancetype)initWithName:(NSString *) name andAge:(int) age;
-(void) show;
@end


#import "Student.h"

@implementation Student
//@synthesize name,age;
- (instancetype)initWithName:(NSString *)name andAge:(int)age
{
self = [super init];
if (self) {
_name=name;
_age=age;
}
return self;
}
-(void)show{
NSLog(@"%@,%d",_name,_age);
}
/**
*  描述信息方法
*此方法 是 对父类的方法重新实现,返回一个字符串对象,此方法,由对象自动调用
《方法重写》
在父类和子类中相同名称的方法,实现不同
*  @return 描述信息
*/
-(NSString *)description{
return [NSString stringWithFormat:@"%@,%d",_name,_age];
}
@end


#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//        Student *stu1=[[Student alloc] initWithName:@"a" andAge:22];
//        Student *stu2=[[Student alloc] initWithName:@"b" andAge:21];
//        Student *stu3=[[Student alloc] initWithName:@"c" andAge:20];
Student *stu1=[[Student alloc] init];
stu1.name=@"qll";
stu1.age=22;
Student *stu2=[[Student alloc] init];
stu2.name=@"zy";
stu2.age=21;
Student *stu3=[[Student alloc] init];
stu3.name=@"zyj";
stu3.age=22;
//创建集合并添加学生的类型的对象当元素
NSArray *arr=[NSArray arrayWithObjects:stu1,stu2,stu3,nil];

//遍历集合元素 通过快速枚举实现
//        for ( Student *a in arr){
////            NSLog(@"%@",[a description]);
//            NSLog(@"%@",a);
//        }

//id identity 标识 任意类型,不用加上 *
for (id stu in arr) {
NSLog(@"%@",stu);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: