objective-c(接口&实现)

objective-c在xcode6下的例子:

  • 定义接口
#import <Foundation/Foundation.h> //基础库,类似C中的stdlib



typedef enum eType {type1 = 1,type2,type3} ETYPE; //OC中对enum、#define、typedef的使用与在C中基本无差异 @interface Teacher : NSObject{

    int tid;

    NSString *name;

    ETYPE type;

}


//peoperty定义这个类的属性,这些属性替代了java中getXXX的方法; @property
int tid; @property NSString *name; @property ETYPE type; -(void) setName: (NSString*)name andId:(int)tid andType:(ETYPE)type; -(void) print; @end
  •  实现
#import "Teacher.h"



#import <Foundation/Foundation.h>



@implementation Teacher



@synthesize tid,name,type; //标示所声明的属性 -(void)setName:(NSString *)inputname andId:(int)inputtid andType:(ETYPE)inputtype{

    self.tid  = inputtid; //self相当于this

    self.name = inputname;

    self.type = inputtype;

}



-(void) print{

    NSLog(@"%@ and %i and type %i", self.name,self.tid,self.type);   

}



@end
  • 测试
#import <Foundation/Foundation.h>

#import "Student.h"

#import "Teacher.h"



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

    @autoreleasepool {

        

        Student *tmp1 = [[Student alloc]init];

        [tmp1 setName:@"fredric" andId:18];

//id object

        id data; //指向NSObject的指针,下面这个例子可以实现类似多态的功能   

        data = tmp1;

        [data print];        

    }

    return 0;

}

你可能感兴趣的:(Objective-C)