//類的聲明
@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] );
方法的重載