一,类的声明
类的声明包括两部分,声明部分及实现部分,下面以Person类的声明为例:
1 Person.h: .h文件中主要是对类的声明(包括实例变量及方法等)
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
//实例变量的声明
int identify;
int age;
}
//方法的声明 以-开头的为实例方法, 以 + 开头的为类方法(实例方法即java中的成员方法,而类方法为静态方法以类名调用)
- (id) initWithAge: (int) _age identify: (int) _identify;
- (int) age;
- (int) identify;
- (void) setAge: (int) _age;
@end
2 Person.m: .m文件中主要是类的实现(如方法的实现等)
#import "Person.h"
@implementation Person
- (id) initWithAge: (int) _age identify: (int) _identify
{
if (self = [super init])
{
age = _age;
identify = _identify;
}
return self;
}
- (int) age
{
return age;
}
- (int) identify
{
return identify;
}
- (void) setAge: (int) _age
{
age = _age;
}
@end
二,类的实例化
先看代码:
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
//对象的初始化及内存分析
//初始化:先用alloc分配内存空间,再调用init方法进行初始化
Person *person;
//kperson = [[Person alloc] init];
//NSLog(@"p = %p", person);
person = [[Person alloc] initWithAge:30 identify:360424];
NSLog(@"person.age: %d ", [person age]);
int age = 31;
[person setAge:age];
NSLog(@"person.age2: %d ", [person age]);
[person setAge:++age];
NSLog(@"person.age3: %d", [person age]);
}
return 0;
}
在oc中,除了基本数据类型,其它均为指针数据类型,指针数据类型初始化时,要用alloc分配内存空间,并调用init方法进行初始化。。。
如person的初始化,[[Person alloc] init]调用时,在堆内存中分配了一块空间存放一个Person对象,而person是栈内存中一个变量,它指向堆 内存中Person对象所在的地址。。。。