Objective-C 類,執行個體成員,靜態變數,對象方法,類方法(靜態方法),對象,
|
在ios中,類的聲明和實現時分離的,也就是說不能寫在同一個檔案中,聲明放在 .h檔案中,實現放在 .m 檔案中。在實現檔案中引入 .h檔案,#import "xxx.h"
聲明一個類:
#import <Foundation/Foundation.h>
@interface Person : NSObject
@end
實現一個類:
#import "Person.h"
@implementation Person
@end
在ios類中吧變數叫做執行個體變數,並且預設許可權為 protected,在類中只能聲明執行個體變數,必能聲明方法。並且不能在 .h檔案中聲明靜態執行個體變數,只能在 .m聲明和使用。
Eg:
#import <Foundation/Foundation.h>
@interface Person : NSObject{
int age ;
NSString* name; //ios中的字串
//static int dwint; error ,can't
}
@end
不能在 .h檔案中聲明靜態執行個體變數,只能在 .m聲明和使用。
Eg:
#import "Person.h"
@implementation Person
static int dwint=20;
@end
對象方法不能在括弧中聲明,只能在括弧外聲明,並且在前面加上 - 。
#import <Foundation/Foundation.h>
@interface Person : NSObject{
int age ;
NSString* name; //ios中的字串
}
-(int)getAge;
-(NSString*)getName;
-(void)setAge:(int)_age;
-(void)setName:(NSString*)_name;
-(void)setAge:(int)_age andName:(NSString*)_name;
@end
實現 .m
#import "Person.h"
@implementation Person
static int dwint=20;
-(int)getAge{
return age;
}
-(NSString*)getName{
return name;
}
-(void)setAge:(int)_age{
age=_age;
}
-(void)setName:(NSString*)_name{
name=_name;
}
-(void)setAge:(int)_age andName:(NSString*)_name{
age=_age;
name=_name;
}
+(int)getStatic{
return dwint;
}
@end
類方法不能在括弧中聲明,只能在括弧外聲明,並且在前面加上 + 。
#import <Foundation/Foundation.h>
@interface Person : NSObject{
int age ;
NSString* name; //ios中的字串
}
-(int)getAge;
-(NSString*)getName;
-(void)setAge:(int)_age;
-(void)setName:(NSString*)_name;
-(void)setAge:(int)_age andName:(NSString*)_name;
+(int)getStatic;
@end
實現 .m
#import "Person.h"
@implementation Person
static int dwint=20;
-(int)getAge{
return age;
}
-(NSString*)getName{
return name;
}
-(void)setAge:(int)_age{
age=_age;
}
-(void)setName:(NSString*)_name{
name=_name;
}