练习(数组)

来源:互联网 发布:c语言||什么意思 编辑:程序博客网 时间:2024/04/28 04:52

Student.h

#import <Foundation/Foundation.h>

@interface Student : NSObject{
    NSString *name;
    int age;
}
@property (copy,nonatomic) NSString *name;
@property int age;

-(void) print;
-(NSComparisonResult) compareName:(id) element;

@end


Student.m

#import "Student.h"

@implementation Student
@synthesize name,age;

-(void) print{
    NSLog(@"name is %@,age is %i",name,age);
}

-(NSComparisonResult) compareName:(id)element{
    return [name compare:[element name]];
}
@end


main.m

#import <Foundation/Foundation.h>
#import "Student.h"

int main (int argc, const char * argv[])
{

    @autoreleasepool {
        
        // insert code here...
        /*NSArray *city = [NSArray arrayWithObjects:@"北京",@"上海",@"杭州",@"苏州",@"天津",@"武汉", nil];
       // if ([city indexOfObject:@"杭州"] == NSNotFound) {
            //NSLog(@"杭州未在其中");
        //}else{
            //NSLog(@"杭州身在其中");
        //}
        
        //for (int i=0; i < [city count]; i++) {
            //NSLog(@"%@",[city objectAtIndex:i]);
        }*/
        
        
        
        //NSMutableArray *city = [[NSMutableArray alloc] init];
        //[city addObject:@"北京"];
        //[city addObject:@"上海"];
        //[city addObject:@"杭州"];
        //[city removeObjectAtIndex:1];
        
        //NSMutableArray *nsma = [NSMutableArray arrayWithCapacity:20];
        
        /*for (int p = 1; p <= 50; p++) {
            if (p%3 == 0) {
                [nsma addObject:[NSNumber numberWithInteger:p]];
            }
        }
        
        for (int i = 0; i < [nsma count]; i++ ){
            NSLog(@"%li",(long)[[nsma objectAtIndex:i] integerValue]);
        }*/
        
        Student *stu1 = [[Student alloc] init];
        Student *stu2 = [[Student alloc] init];
        Student *stu3 = [[Student alloc] init];
        
        [stu1 setName:@"Sam"];
        [stu1 setAge:30];
        [stu2 setName:@"Lee"];
        [stu2 setAge:23];
        [stu3 setName:@"Alex"];
        [stu3 setAge:26];
        
        NSMutableArray *students = [[NSMutableArray alloc] init];
        [students addObject:stu1];
        [students addObject:stu2];
        [students addObject:stu3];
        
        NSLog(@"排序前");
        for (int i=0; i < [students count]; i++) {
            Student *stu4 = [students objectAtIndex:i];
            NSLog(@"Name:%@,Age:%i",[stu4 name],[stu4 age]);
        }
        
        [students sortUsingSelector:@selector(compareName:)];
        
        NSLog(@"排序后");
        for (Student *stu4 in students) {
            NSLog(@"Name:%@,Age:%i",stu4.name,stu4.age);
        }
        
    }
    return 0;
}