OC入門筆記

1.OC類
.h文件  類、函數的生命  @interface @end
.m文件  類的具體實現    @implementation  @end

2.創建OC對象
Dog *dog=[Dog alloc];  alloc=new
初始化構造函數
[dog init];
銷燬
[dog release];

3.類中字段和函數
@interface Dog:NSObject{
//定義字段
int age;
}
-(void) setAge:(int)newAge;
//定義函數
@end

4.字段定義

@public  @protected @private  缺省@protected

Dog.h   
@interface Dog:NSObject
{
 @public  
 int age;
 @protected
 int ID;
 @private 
 float price;
 }
 @end
 
5.類得聲明
Dog * myDog;
*表示指針,也表示引用
可以通過myDog-->dog  或者myDog.dog這些方法來訪問


6.典型(example)
Dog.h

#import <Foundation/Foundation.h>
@interface Dog:NSObject{
int age;
}
-(id) init;
-(id) initWithAge:(int)newAge;
-(int)getAge;
-(void)setAge:(int)newAge;

@end
------------------------------------------------
Dog.m

#import "Dog.h"
@implementation Dog
-(id)init{
  return [self initWithAge:10];
}
-(id)initWithAge:(int)newAge{
  self=[super init];
  if(self){
     age=newAge;  
  }
  return self;
}
....


6.函數定義
O-C屬性聲明 只能在@interface{和}之間
方法定義
-(int)f:(int)x;
這裏的-表示對象的方法,+表示類得方法


-(int) insertObject:(NSObject *)o  AtIndex:(int)index
        Before:(BOOL)before
  int ret=[obj insertObject:10 AtIndex:2 Before:TRUE]
  
7.函數重載
OC不是嚴格的函數重載

@interface Foo:NSObject{
}
-(int) g:(int)x;
-(int) g:(float)x; //錯誤 方法衝突 (無標籤)
-(int) g:(int)x:(int)y; 
-(int) g:(int)x:(float)y; //錯誤
函數類型 不管 --只管函數名

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章