##《Objective-C 高级编程》测试题
设计一个动物基类。 要求: A、抽象出动物的基本属性(包括:性别、名字、体重)。 B、抽象出动物的基本能力(包括:发声)。 C、基本属性性别用枚举定义。
由题目 1 设计好的动物基类继承,设计一个新的鸟和鱼的子类。 要求: A、鸟类需要扩展颜色属性。 B、鸟类需要扩展飞的方法(方法体输出打印出飞行状态即可)。 C、鱼类需要扩展颜色属性。 D、鱼类需要扩展出游的方法(方法体输出打印游的状态即可)。
设计好 1、2 两个题目要求的类后,创建一个数组。使用一个循环,生成 10 只鸟、10 条鱼的对象,并将 10 只鸟、10 条鱼的对象加入到创建好的数组中。 最后,遍历这个数组对象,遍历到鸟对象时调用鸟儿飞的方法,遍历到鱼对象 时调用鱼儿游的方法。
考虑游戏中捞鱼, 随机器捞到 n 条鱼,纪录数量(被捞到的鱼认为对象的生 命周期结束,需要从内存中释放)。打鸟同理。
我的实现 github 源码:BLTest1
复习了类的定义,属性,实例方法,枚举,NSArray,随机数。 @孔祥波 老师点评了我的错误实现。自己回来改了很多,终于完成了,也加深了涉及知识点的应用。再次感觉 Google 真是个好东西。
###实现代码位置:
一二题目定义类为:GWAnimal,GWBird,GWFish
三四题对应代码在:ViewController.m 的 - (void)viewDidLoad {}中 分别添加 // MARK No.3 和 // MARK: No.4,方便定位。
注释文档 其他的 Headerdoc 为练习写注释文档,尤其是// FIXME: Print a more readable result. 和 // TODO: Set a NSArray to init randomGWFish. 纯粹凑字数。测试 Swift 哪些可以用在 Objective-C 上。参看: Swift Documentation 。
其实这个实现是 Objective-C,应该看这一篇的 Documentation :
@param [param] [Description]: Describes what value should be passed for this parameter
@return [Description]: Describes the return value of the method
@see [selector]: Provide “see also” reference to related method
@warning [description]: Call out exceptional or potentially dangerous behavior
To help speed up the process of documenting your project, you may want to check out the VVDocumenter-Xcode project , which automatically adds @param and @return labels for methods according to their signature.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 NSMutableArray *animal = [[NSMutableArray alloc] init];for (int i = 0 ; i < 10 ; i++) { NSArray *birdNames = @[@"Parrot" , @"Pelican" , @"Raptor" , @"Ural" , @"Owls" , @"BABY BLUE" , @"AIDEN" , @"BB" , @"DAVE" , @"CHILI" ]; GWBird *randomGWBird = [[GWBird alloc] initWithName:birdNames[i] gender:(Gender)(arc4random() % 2 ) weight:(NSUInteger )(arc4random() % 100 )]; randomGWBird.color = [UIColor whiteColor]; [animal addObject:randomGWBird]; GWFish *randomGWFish = [[GWFish alloc] initWithName:@"Fish" gender:(Gender)(arc4random() % 2 ) weight:(NSUInteger )(arc4random() % 100 )]; randomGWFish.color = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0 ]; [animal addObject:randomGWFish]; } for (int i = 0 ; i < [animal count]; i++) { if ([animal[i] isKindOfClass:[GWBird class ]]) { [animal[i] fly]; } else if ([animal[i] isKindOfClass:[GWFish class ]]) { [animal[i] swim]; } } int fishCount = 0 ;int birdCount = 0 ;NSUInteger randomRemoveNumber = (NSUInteger )(arc4random() % 20 );for (NSUInteger i = randomRemoveNumber; i > 0 ; i--) { NSUInteger randomIndex = (NSUInteger )(arc4random() % i); [animal removeObjectAtIndex:randomIndex]; if ([animal[randomIndex] isKindOfClass:[GWBird class ]]) { birdCount++; } else if ([animal[randomIndex] isKindOfClass:[GWFish class ]]) { fishCount++; } } NSLog (@"fishCount:%d, birdCount:%d, randomRemoveNumber:%lu, [animal count]:%lu" , fishCount, birdCount, (unsigned long )randomRemoveNumber, (unsigned long )[animal count]);