IOS开发笔记 (3)---objective c 自己编写测试示例
为了更好的使得自己理解并掌握oc的语法,我在看完大部分oc的基础后,开始自己在notepad++上编辑一个测试的示例程序。
本以为很简单的几个类的程序,让我调试了好长时间,看来这种代码的编写方式真的是不错。让我对一些细小的地方更加的留意。
测试的程序主要包含了一个父类Animal、一个子类Dog、一个category-DogExt、一个protocol Print以及一个测试主程序文件main.
测试结果如下:有一点不符合我的预期结果,就是函数instancesRespondToSelector. Dog这个类明明有一个类方法printDogCount
可是结果却显示没有这个函数。后来我直接performSelector却可以执行了。同时我知道NSObject包含了一个返回类名的方法class
我将@selector(printDogCount)替换为@selector(class)却完美执行。真是奇怪!!!难道是bug不成。以后在关注吧。
测试结果:
Animal initialize
Dog initialize
There is 1 Dog(s)
2011-11-05 00:35:12.989 Hello[1339:707] Buddy
2011-11-05 00:35:12.990 Hello[1339:707] Wow!
There is 4 feet of Dog!
There is 2 Dog(s)
2011-11-05 00:35:12.991 Hello[1339:707] Tom
2011-11-05 00:35:12.992 Hello[1339:707] Wow!
dog is not a member Animal
dog is kind of Animal
dog respondsToSelector 'Wow' and performs it
2011-11-05 00:35:12.992 Hello[1339:707] Buddy
2011-11-05 00:35:12.993 Hello[1339:707] Wow!
Dog not instancesRespondToSelector 'printDogCount'
There is 2 Dog(s)
dog can play ball by category ext
2011-11-05 00:35:12.993 Hello[1339:707] Buddy has 4 feet
dog conformsToProtocol Print
There is 3 Dog(s)
dog3 retain count=1
dog3 retain count=2
dog3 retain count=3
dog3 retain count=2
dog3 retain count=1
There is 2 Dog(s)
There is 1 Dog(s)
There is 0 Dog(s)
源码
Animal.h
/*
Animal Class
*/
#import <Foundation/Foundation.h>
#import "Print.h" //a protocol
@inte易做图ce Animal : NSObject <Print>
{
NSString* _name;
}
-(Animal*) init;
-(void) Wow;
-(int) FeetNumber;
-(NSString*) Name;
-(void) setName : (NSString*) name ;
@end
Animal.m
#import "Animal.h"
#import <stdio.h>
@implementation Animal
+(void) initialize {
printf("Animal initialize\r\n");
}
-(Animal*) init
{
self = [super init];
_name = [[NSString alloc] initWithString : @"Animal"]; //自己分配内存
return self;
}
-(void) dealloc
{
[_name release];
}
-(void) Wow
{
printf("Animal Wow!\r\n");
}
-(int) FeetNumber
{
return -1;
}
-(NSString*) Name
{
return _name;
}
-(void) setName : (NSString*)new_name
{
[_name release]; //释放内存
_name = [new_name copy]; //拷贝后存放
}
//protocol
-(void) Print
{
NSString* str = [[NSString alloc] initWithFormat:@"%@ has %i feet\r\n",_name,[self FeetNumber]];
NSLog(@"%@",str);
[str release];
}
@end
Dog.h
#import <Foundation/Foundation.h>
#import "Animal.h"
@inte易做图ce Dog : Animal
{
@public //测试成员变量存取权限
int public_var;
@protected
int protected_var;
}
+(void) printDogCount; //类方法
@end
Dog.m
#import "Dog.h"
#import <stdio.h>
@implementation Dog
static int count = 0; //类似与类的静态变量
+(void) initialize {
printf("Dog initialize\r\n");
}
-(Dog*) init
{
self = [super init];
[self setName : @"Dog" ];
count ++ ;
[Dog printDogCount];//调用类方法
return self;
}
-(void) dealloc
{
count --;
[Dog printDogCount];
[super dealloc];
}
+(void) printDogCount
{
printf("There is %d Dog(s)\r\n",count);
}
-(void) Wow
{
NSLog(@"%@",[self Name]);
NSLog(@" Wow!\r\n");
}
-(int) FeetNumber //狗有四条腿
补充:综合编程 , 其他综合 ,