// // main.m #import <Foundation/Foundation.h> #import "Person.h" /* <span style="white-space:pre"> </span>1 创建集合 2 通过构造方法的方式创建一个NSArray 3 数组中可以存储不同类型的对象 4 数组实际上是存储的是对象的地址,同样也可以存储数组的地址 5 存储自定义的对象 6 数组中存储基本数据类型 7 创建数组的快捷方式 8 快速获得一个数组中的元素 9 从集合中取出数据 10 获得数组的元素个数 11 判断数组中是否存在某个对象 */ int main(int argc, const char * argv[]) { @autoreleasepool { // 1 创建集合 NSArray * array = [[NSArray alloc] initWithObjects:@"one",@"two",@"three", nil]; NSLog(@"array %@",array); NSArray * array1 = @[@"one",@"two",@"three"]; NSLog(@"array1 %@",array1); // int float char double bool int i = 10; NSNumber * number = [[NSNumber alloc] initWithInt:i]; //3 数组中可以存储不同类型的对象 NSArray * array2 = @[@"one",@"two",number]; NSLog(@"array2 %@",array2); // 4 数组中实际是存储的对象的地址 数组中也可以存储地址 NSArray * a1 = @[@"one",@"two",@"three"]; NSArray * a2 = @[@"1",@"2",@"3"]; NSArray * a3 = @[a1,a2]; NSLog(@"a3 %@",a3); NSString * str = nil; // 此方法中最后一个元素必须是 nil 如果数组中存储 nil 元素容易导致数据丢失 NSArray * array3 = [[NSArray alloc] initWithObjects:@"one",str,a3,@"three", nil]; NSLog(@"%@",array3); // 创建三个 Person 对象存入数组中 Person * p1 = [[Person alloc] initWithName:@"Jack" andAge:15]; Person * p2 = [[Person alloc] initWithName:@"Tom" andAge:18]; Person * p3 = [[Person alloc] initWithName:@"Jim" andAge:20]; NSArray * array4 = [[NSArray alloc] initWithObjects:p1,p2,p3, nil]; NSLog(@"%@",array4); //6 数组中存储基本数据类型 // + (NSNumber *)numberWithChar:(char)value; // + (NSNumber *)numberWithInt:(int)value; // + (NSNumber *)numberWithFloat:(float)value; // + (NSNumber *)numberWithDouble:(double)value; // + (NSNumber *)numberWithBool:(BOOL)value; // + (NSNumber *)numberWithInteger:(NSInteger)value // 用 NSNumber 将基本数据类型包装后存入数组 NSNumber * number1 = [NSNumber numberWithFloat:8.9]; NSNumber * number2 = [NSNumber numberWithInt:8]; NSNumber * number3 = [NSNumber numberWithDouble:8.9345]; NSNumber * number4 = [NSNumber numberWithChar:'c']; NSArray * array5 = [[NSArray alloc] initWithObjects:number1,number2,number3,number4, nil]; // char 类型存储的是 ASCII 码值 NSLog(@"%@",array5); char c = [[array5 objectAtIndex:3] charValue]; NSLog(@"%c",c); // 数组取元素 Person * p4 = [array4 objectAtIndex:1]; NSLog(@"%@",p4); // 取元素的快速方法 Person * p5 = array[1]; } return 0;
#import <Foundation/Foundation.h> @interface Person : NSObject { NSString * _name; int _age; } - (id)initWithName:(NSString *)name andAge:(int)age; - (void)setName:(NSString *)name; - (NSString *)name; - (void)setAge:(int)age; - (int)age; @end
#import "Person.h" @implementation Person - (id)initWithName:(NSString *)name andAge:(int)age { if (self = [super init]) { _name = name; _age = age; } return self; } - (void)setName:(NSString *)name { _name = name; } - (NSString *)name { return _name; } - (void)setAge:(int)age { _age = age; } - (int)age { return _age; } - (NSString *)description { return [NSString stringWithFormat:@"name = %@, age = %d",_name,_age]; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u012701023/article/details/47052781