Objective-C 類,執行個體成員,靜態變數,對象方法,類方法(靜態方法),對象,

來源:互聯網
上載者:User
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;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.