OC 类的定义
@interfance SimpleClass:NSObject
@endOC 类的声明以@interface 开始,以@end 结束,以:标识父类
类的属性声明
@interface Person:NSObject
@property NSString *FirstName;
@property NSString *lastName;
@end
<span style="font-size:18px;">
</span>声明了一个 Persion 类 ,@property 关键字定义一个属性(类变量),NSString *FirstName 中OC 类中用{}定义成员变量,+ -分别表示静态方法(类方法)和动态方法(对象方法),用.h 文件保存声明,.m 文件保存实现
#import <Foundation/Foundation.h>
@interface Student : NSObject {
int age; // 年龄
@public//可以省略.h 中声明的所有方法都是 public的
int no; // 学号
int score; // 成绩
@protected
float height; // 身高
@private
float weight; // 体重
}
// age的get方法
- (int)age;
// age的set方法
- (void)setAge:(int)newAge;
@endOC 中用(int)来标明返回值,用:来写明参数,一个冒号对应一个返回值,冒号本身是方法名字的一部分,比如 getAge 不是方法名,getAge:才是
分别用@public @private @protected 来标识作用域
OC 类的实现
OC 中类的实现以@implentation 开始以@end 结束,
#import "Student.h"
@implementation Student
// age的get方法
- (int)age {
// 直接返回成员变量age
return age;
}
// age的set方法
- (void)setAge:(int)newAge {
// 将参数newAge赋值给成员变量age
age = newAge;
}
// 同时设置age和height
- (void)setAge:(int)newAge andHeight:(float)newHeight {
age = newAge;
height = newHeight;
}
@end OC 对象的创建OC方法调用使用[调用者 被调用者 ]的格式,其中调用者一般是类名或者对象名
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Student *stu = [[Student alloc] init];
[stu release];
}
return 0;
}其中 alloc 调用者是类名,init 调用者是对象
本文详细介绍了Objective-C类的定义、声明、属性声明、类实现及对象创建过程,包括成员变量、静态方法和动态方法的使用,以及类的作用域标识符。通过实例展示了如何在Objective-C中创建类并实现其方法。
235

被折叠的 条评论
为什么被折叠?



