// // main.m // OC-遍历和排序-homework // // Created by dllo on 16/2/25. // Copyright © 2016年 dllo. All rights reserved. // #import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { // 要求 : // 1、创建1个包含5个字符串元素的数组; 2、 for循环倒序输出所有元素; 3、 for...in完成所有字符串元素的拼接( 成 个 // 新的字符串),并输出拼接好的字符串。 NSArray *strArray = @[@"nanjing", @"shanghai", @"beijing", @"shangxi", @"chongqing"]; for (int i = 0; i < strArray.count; i++) { NSLog(@"%@", [strArray objectAtIndex:strArray.count - 1 - i]); } NSMutableString *str = [NSMutableString stringWithCapacity:20]; for (NSString *string in strArray) { [str appendString:string]; } NSLog(@"%@", str); // 要求: // 1、创建1个包含5个person对象的数组(姓名 英 ); 2、 for循环找到年龄最 的Person对象; 3、 for...in遍历数组,把 于某个年龄的Person对象的姓名后 拼接上字符串“-brother”。 Person *per1 = [[Person alloc]initWithName:@"ma" sex:@"male" age:26]; Person *per2 = [[Person alloc]initWithName:@"liutaifeng" sex:@"male" age:22]; Person *per3 = [[Person alloc]initWithName:@"zhengfeng " sex:@"male" age:23]; Person *per4 = [[Person alloc]initWithName:@"ma" sex:@"male" age:27]; Person *per5 = [[Person alloc]initWithName:@"ma" sex:@"male" age:29]; NSArray *array = [NSArray arrayWithObjects:per1, per2, per3, per4, per5, nil]; Person *per = [[Person alloc]initWithName:@"majian" sex:@"male" age:29]; for (int i = 0; i < array.count; i++) { if ([[array objectAtIndex:i] age] < [per age]) { per = [array objectAtIndex:i]; } } NSLog(@"%@", [per name]); NSArray *newArray = [array sortedArrayUsingSelector:@selector(compareWithName:)]; NSLog(@"%@", newArray); NSArray *newArray2 = [array sortedArrayUsingSelector:@selector(compareWithSex:)]; NSLog(@"%@", newArray2); NSArray *newArray3 = [array sortedArrayUsingSelector:@selector(compareWithAge:)]; NSLog(@"%@", newArray3); NSSortDescriptor *sortOfName = [[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES]; NSSortDescriptor *sortOfAge = [[NSSortDescriptor alloc]initWithKey:@"age" ascending:YES]; NSArray *array1 = [array sortedArrayUsingDescriptors:@[sortOfName, sortOfAge]]; NSLog(@"%@", array1); } return 0; }
Person.m文件:
// // Person.m // OC-遍历和排序-homework // // Created by dllo on 16/2/25. // Copyright © 2016年 dllo. All rights reserved. // #import "Person.h" @implementation Person - (instancetype)initWithName:(NSString *)name sex:(NSString *)sex age:(NSInteger)age{ self = [super init]; if (self) { _name= name; _age = age; _sex = sex; } return self; } - (NSComparisonResult)compareWithName:(Person *)anOtherPerson{ return [self.name compare:anOtherPerson.name]; } - (NSComparisonResult)compareWithAge:(Person *)anOtherPerson{ if (self.age > anOtherPerson.age) { return NSOrderedDescending; }else if(self.age < anOtherPerson.age){ return NSOrderedAscending; }else{ return NSOrderedSame; } } - (NSComparisonResult)compareWithSex:(Person *)anOtherPerson{ return [self.sex compare:anOtherPerson.sex]; } - (NSString *)description { return [NSString stringWithFormat:@"name:%@, sex:%@, age:%ld", _name, _sex, _age]; } @end