天天看点

类的声明和对象的创建、@property属性和点语法、类的继承

//类的声明
@interface Person : NSObject
{
    //实例变量的声明
    int identify;
    int age;
}
//方法声明
- (id) initWithAge:(int) _age identify:(int) _identify;
- (int) getIdentify;
- (int) getAge;
- (void) setAge:(int) _age;
@end

//类的实现
@implementation Person
- (void) initWithAge:(int) _age identify _identify
{
    if (self = [super init]) {
        age = _age;
        identify = _identify;
    }
    return self;
}

- (int) getIdentify
{
    return identify;
}

- (int) getAge
{
    return age;
}
- (void) setAge: (int) _age
{
    age = _age;
}

@end


对象的创建
Person * person;    // nil
person = [[Person alloc] init]; 

//两个的方法,两个方法是否相同,与参数类型和返回值无关
- (int) changed:(int) _age
{

}      
static关键字
类体内的全局变量声明:
static int gCount = 0; //这个值只有一份

//解释属性nonatomic
在@property()括号中,可以填写的属性:
readwrite: 默认
readonly: 只读,意味着没有set方法
assign:默认,引用计数不增加
retain:引用计数增加1
原子性:actomic默认
非原子性:nonatomic
atomic是OC中的一种线程保护技术,是防止在未完成的时候,被另外一个线程使用。造成数据错误。

点语法:
person.myNumber = 100;
NSLog(@"%d", person.myNumber);

简化设置器
@interface Person : NSObject

@property(nonatomic) int myNumber;

@end

//实现部分
@implementation Person

@synthesize myNumber; //多个写多行,或者用逗号隔开也行,例如 @synthesize myNumber, age;

@end



以下是原始的方式
@interface Person : NSObject
{
    int myNumber;     //实例变量
}
- (int) myNumber;
- (void) setMyNumber:(int) _number;
- (void) printfInfo;
@end

@implementation Person
//get方法
- (int) myNumber
{
    return myNumber;
}
//set方法
- (void) setMyNumber:(int) _number
{
    myNumber = _number;
}
//打印本类的信息
- (void) printfInfo
{
    NSLog(@"Person number is : %d", myNumber);
}
@end      
继承的书写
@interface ClassB : ClassA

@end


@interface Rectangle : NSObject
{
    int width;
    int height;
}
@Property (nonatomic) int width,height;
- (int) area;
- (int) perimeter;
- (int) setWidth:(int) w andHeight:(int) h;
@end

@implementation Rectangle
@synthesize width, height;
- (int) area
{
    return width*height;
}
-(int)perimeter
{
    return (width + height) * 2;
}
- (void) setWidth: (int) w andHeight: (int) h
{
    width = w;
    height = h;
}
@end


main方法中代码
Rectangle *myRect = [[Rectangle alloc] init];
[myRect setWidth:6 andHeight:7];
NSLog(@"Rectangle: w = %d, h = %d", myRect.width, myRect.height);
NSLog(@"Rectangle:area = %d perimeter = %d", [myRect area], [myRect perimeter] );

方法的重载