//
// Student.h
// ocDemo
//
// Created by 屎壳郎情调 on 13-8-6.
// Copyright (c) 2013年 ibokan. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Student : NSObject
{
//声明实例变量
@public //全局
NSString *name;
@private //私有 在其他地方stu->age就不能访问
int age;
@protected //包 @protected 默认
NSString *sex;
}
//声明方法 - 表示 实例方法 + 表示 类方法
-(id)init;
-(id)initWithName:(NSString *)newName AndSex:(NSString *)newSex AndAge:(int)newAge;
-(id)initWithAge:(int *)newAge;
-(void)setName:(NSString *)newName;
-(NSString *)getName;
-(void)SayHello;
+(void)Sleep;
+(id)StudentWithName:(NSString *)newName AndSex:(NSString *)newSex AndAge:(int)newAge;
@end
.m部分如下
-(id)init
{
if(self=[super init])
{
name = @"默认名字";
age = 20;
sex = @"默认性别";
}
return self;
}
-(id)initWithAge:(int *)newAge
{
if(self=[super init])
{
age = newAge;
}
return self;
}
-(id)initWithName:(NSString *)newName AndSex:(NSString *)newSex AndAge:(int)newAge
{
if(self=[super init])
{
age = newAge;
name = newName;
sex = newSex;
}
return self;
}
+(void)Sleep
{
NSLog(@"Student Method");
}
+(id)StudentWithName:(NSString *)newName AndSex:(NSString *)newSex AndAge:(int)newAge
{
Student *stu = [[[Student alloc] initWithName:newName AndSex:newSex AndAge:newAge] autorelease];
return stu;
}
注意:
Student *stu = [[Student alloc]init];和
Student *stu = [Student new];等效
访问实例变量 stu->name //前提是 name是 @public @protected @package 才行 @private不能访问到
属性
#import "Student.h"
@interface SmallStudent : Student
{
@public
NSString *sname;
}
//set 写
-(void)setSname:(NSString *)newName;
//get 读
-(NSString *)getSname;//等效的get -(NSString *)sname;
-(void)getInfo;
@end
#import "SmallStudent.h"
@implementation SmallStudent
-(void)getInfo
{
NSLog(@"name:%@,",sname);
}
-(void)setSname:(NSString *)newName
{
sname = newName;
}
-(NSString*)getSname
{
return sname;
}
@end
注意;
SmallStudent *sStu = [[SmallStudent alloc] init];
//[sStu setSname:@"dasd"];//就算私有的 都可以设置
sStu.sname = @"aaaa";//有get set之后才可以
//sStu.sname 这个sname不是实例变量名 而是 get set 的方法名对应 对应:getSname
[sStu getInfo];
@property 和
@synthesize之后 我们就不要手动写 get set了
.h里面声明属性@property
.m里面@synthesize
.h里面
@interface SmallStudent : Student
{
//实例变量
@public
NSString *sname;
NSString *_ssex;
}
//属性 @property NSString *sname;等效于下面的get set
-(void)setSname:(NSString *)newName;
-(NSString *)getSname;//等效的get -(NSString *)sname;
//如果等号后面没有东西 默认实例变量名和 属性名一样
@synthesize sname;
//@synthesize 属性名 = 实例变量名
@synthesize ssex = _ssex ;[_ssex release];//[self.ssex release];在iOS6之后会内存泄漏