Objective-C 类,实例成员,静态变量,对象方法,类方法(静态方法),对象,

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;
}

-(void)setAge:(int)_age andName:(NSString*)_name{

// 可以一次set多个 实例变量 并且标签名可以随意,也可以不写,其中setAge,andName 都是标签。

    age=_age;
    name=_name;
}
+(int)getStatic{
    return dwint;
}
@end

六、对象


#import <Foundation/Foundation.h>
#import "Circle.h"
#import "Person.h"

int main (int argc, const char * argv[])
{

    @autoreleasepool {

        NSLog(@"Hello, World!");
        NSString* str_name=@"shouqiang_Wei"; // 在这里字符串前面必须加上@
        Person* person=[[Person alloc] init]; //这里使用 [类名 函数名] 的形式 所以 init 是一个类方法,并且是一个默认构造,用来初始化对象,
        [person setAge:30 andName:str_name];
        NSLog(@"age = %d ,name = %@",[person getAge],[person getName]); // %@输出Object 类型

    }
    return 0;
}

posted on 2013-08-14 19:24  you Richer  阅读(591)  评论(0编辑  收藏  举报