标签:style io color ar sp div on 2014 log
/*****************person.h*****************/
/*
程序设计目的:
类具有和C语言结构体相似的特征,每个类创建的对象都会拷贝本类的成员方法(函数又称消息)和成员变量(又称字段)放在自己的内存空间中,以后对象再次调用函数或乘员变量时实际上是调用自己内存中的拷贝,而本例题就是为了证明这一点而专门设计的。
*/
#import <Foundation/Foundation.h>
@class Dog;
@interface Person : NSObject
{
Dog *_dog;
NSString *_name;
NSInteger _age;
}
-(id)initWithName:(NSString *)newName andAge:(NSInteger)newAge;
-(void)showme;
@property(nonatomic,readonly) NSString *name;
-(NSInteger)age;
@property(copy) Dog *dog;
-(void)setDog:(Dog *)dog;
@end
#import "Person.h"
#import "Dog.h"
@implementation Person
-(id)initWithName:(NSString *)newName andAge:(NSInteger)newAge{
_name = newName;
_age = newAge;
return self;
}
-(void)showme{
NSLog(@"I‘m %@ age:%li",self.name,(long)self.age);
}
-(NSInteger)age{return _age;}
@synthesize dog = _dog;
//方法的实现展开:
-(void)setDog:(Dog *)dog{
if (dog!=_dog) {
//_dog可能为空,OC允许[_dog release];
[_dog release];
_dog = [dog retain];
}
}
@end
#import <Foundation/Foundation.h>
@interface Dog : NSObject
{
int _ID;
}
@property int ID;
-(void)print_counter;
-(void)bug;
@end
#import "Dog.h"
@implementation Dog
//打印目前dog的引用计数(reference counting)的值
-(void)print_counter{NSLog(@"retaincount:%li",[self retainCount]);}
//狗叫:
-(void)bug{ NSLog(@"T‘m a dog!");}
@end
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Dog.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Person *No_1 = [[Person alloc] initWithName:@"Tom" andAge:18];
Person *No_2 = [[Person alloc] initWithName:@"Bieber" andAge:21];
Dog *dog_1 = [[Dog alloc] init];
Dog *dog_2 = [[Dog alloc] init];
Dog *dog_3 = [[Dog alloc] init];
//测试:
[No_1 setDog:dog_1];
[dog_1 print_counter];
[No_2 setDog:dog_2];
[dog_2 print_counter];
[No_1 setDog:dog_3];
[dog_1 print_counter];
[No_1 showme];
[No_2 showme];
/*
输出信息:
2014-11-16 14:57:48.760 Ram_control[1092:303] retaincount:2
2014-11-16 14:57:48.761 Ram_control[1092:303] retaincount:2
2014-11-16 14:57:48.762 Ram_control[1092:303] retaincount:1
2014-11-16 14:57:48.762 Ram_control[1092:303] I‘m Tom age:18
2014-11-16 14:57:48.763 Ram_control[1092:303] I‘m Bieber age:21
*/
//测试结果,一个类的对象会把类里面的成员方法和变量都单独的拷贝一份在自己的内存空间里,(static或全局变量另行讨论)每个对象每次调用的类的成员函数或者成员变量实际上都是自己拷贝的那一份。类似于C语言中的结构体。
}
return 0;
}
标签:style io color ar sp div on 2014 log
原文地址:http://blog.csdn.net/u012360598/article/details/41172981