您的位置:首页 > 其它

OC中类的特点

2016-03-29 00:00 134 查看
OC中的类:

单继承

通过@protocol协议,实现多继承

支持多态

id == void *

nil == null

OC中的类:

žDog.h 类的声明

ž@interface Dog:NSobject{ ž

//只能写字段 ž

} ž

//函数声明这里; ž

@end

žDog.m 类的实现

ž#Improt “Dog.h” ž

@implementation Dog ž ž

//实现方法写这里 ž

@end

新建一个类:

新建一个“Cocoa Touch Class”文件,命名为People

通过手动写入set/get方法:

People.h 写入:

@interface people : NSObject{
int _age;
}

-(void)setAge:(int)age;

-(int) age;

@end

People.m 写入:

#import "people.h"

@implementation people

-(void)setAge:(int)age{
_age = age;
}
-(int)age{
return _age;
}

@end

使用场合:

#import <Foundation/Foundation.h>
#import "people.h"

int main(int argc, const char * argv[]) {
@autoreleasepool {
people *p1 = [[people alloc]init];

p1.age = 10;

NSLog(@"%d", p1.age);

}
return 0;
}

通过@property方式自动会产生set/get方法:

People.h 写入:
#import <Foundation/Foundation.h>

@interface people : NSObject

@property (assign)int age;

@end


People.m 写入:
#import "people.h"

@implementation people

@synthesize age;

@end

使用场合:

#import <Foundation/Foundation.h>
#import "people.h"

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

people *p1 = [[people alloc]init];
p1.age = 30;
NSLog(@"%d", p1.age);

}
return 0;
}


权限控制:

@public //任何地方可以使用
ž@private//私有的 只能再本类使用
ž@protected //默认的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: