Object-C学习笔记(三)-----实体类和for循环以及NSMutableArray的连用

来源:互联网 发布:淘宝新浪博客 编辑:程序博客网 时间:2024/06/06 04:09

这里 我采用NSMutableArray 而不使用NSArray,是受了java的影响,前者接近java中的List,后者却接近java中的数组;


NSMutableArray长度可以不确定,可以在末尾继续添加对象,操作起来也比较方便。   具体 NSMutableArray和NSArray的区别,请参考下面的文章,介绍的很清楚;


http://blog.csdn.net/ganlijianstyle/article/details/7611776


NSArray中常用的方法,请参考下面的文章,介绍的很清楚:


http://blog.csdn.net/onetoneom/article/details/7894564



下面记下自己写的例子:


项目结构图如下:




Student.h

#import <Foundation/Foundation.h>@interface Student : NSObject{    int age;    NSString *name;    } -(void) setAge:(int)a;-(void) setName:(NSString *) n;-(int) getAge;-(NSString *) getName;@end


Student.m

#import "Student.h"@implementation Student-(void) setAge:(int)a{    age=a;}-(void)setName:(NSString *)n{    name=n;}-(NSString *)getName{      return name;}-(int)getAge{    return age;}@end


Opeartion.h

#import <Foundation/Foundation.h>@interface Opeartion : NSObject+(void)arropeartion1;+(void)arropeartion2;@end


Opeartion.m


#import "Opeartion.h"#import "Student.h"@implementation Opeartion+(void)arropeartion1{    Student *student1=[[Student alloc] init];    [student1 setName:@"郭靖"];    [student1 setAge:20];        Student *student2=[[Student alloc] init];    [student2 setName:@"黄蓉"];    [student2 setAge:19];        NSMutableArray *arr=[[NSMutableArray alloc] init];    [arr addObject:student1];    [arr addObject:student2];        [student1 release];    [student2 release];        for (int i=0; i<[arr count]; i++) {        Student *stu=[arr objectAtIndex:i];        NSLog(@"姓名:%@, 年龄:%i",[stu getName],[stu getAge]);        [stu release];    }          }+(void)arropeartion2{    NSMutableArray *array=[[NSMutableArray alloc] init];        for (int i=0; i<10; i++) {        Student *stu=[[Student alloc] init];        [stu setAge:i];        [stu setName:@"郭靖"];        [array addObject:stu];        [stu release];    }        for (int i=0; i<[array count]; i++) {        Student *st=[array objectAtIndex:i];        NSLog(@"姓名: %@    ,  年龄: %i ", [st getName], [st getAge]);        [st release];    }       }@end

main.m


#import <Foundation/Foundation.h>#import "Student.h"#import "Opeartion.h"int main(int argc, const char * argv[]){    @autoreleasepool {                    [Opeartion arropeartion1];                NSLog(@"---------------");                [Opeartion arropeartion2];            }    return 0;}