7.2,实现步骤
第一步,按照我们在第2章所述的方法,新建一个项目,项目的名字叫做07-InitWithAndIvarScope。
第二步,按照我们在第4章的4.2节的第二,三,四步所述的方法,把在第4章已经使用过的“Cattle.h”,“Cattle.m”,“Bull.h”还有“Bull.m”, 导入本章的项目里面。然后把第6章里面的“MyNSobjecs.h”也导入到项目当中。
第三步,打开“Cattle.h”,修改成为下面的代码并且保存:
#import
@interface Cattle : NSobjecs {
int legsCount;
@private
bool gender; //male = YES female = NO
@protected
int eyesCount;
@public
NSString *masterName;
}
- (void)saySomething;
- (void)setLegsCount:(int) count;
- (id)initWithLegsCount:(int) theLegsCount
gender:(bool) theGender
eyesCount:(int) theEyesCount
masterName:(NSString*)theMasterName;
@end
第4步,打开“Cattle.m”,修改成下面的代码并且保存:
#import "Cattle.h"
@implementation Cattle
-(void) saySomething
{
NSLog(@"Hello, I am a cattle, I have %d legs.", legsCount);
}
-(void) setLegsCount:(int) count
{
legsCount = count;
}
-(id)init
{
[super init];
return [self initWithLegsCount:4
gender:YES
eyesCount:2
masterName:@"somebody"];
}
- (id)initWithLegsCount:(int) theLegsCount
gender:(bool) theGender
eyesCount:(int) theEyesCount
masterName:(NSString*)theMasterName
{
legsCount = theLegsCount;
gender = theGender;
eyesCount = theEyesCount;
masterName = theMasterName;
return self;
}
@end
第五步,打开“Bull.m”, ,修改成下面的代码并且保存:
#import "Bull.h"
@implementation Bull
-(void) saySomething
{
NSLog(@"Hello, I am a %@ bull, I have %d legs.", [self getSkinColor],legsCount);
NSLog(@"I have %d eyes, my master is %@.", eyesCount,masterName);
//List below is illegal
//NSLog(@"My gender is %@",gender ? @"male" : @"female");
}
-(NSString*) getSkinColor
{
return skinColor;
}
- (void) setSkinColor:(NSString *) color
{
skinColor = color;
}
@end
第六步,打开“07-InitWithAndIvarScope.m”,修改成下面的代码并且保存:
#import
#import "Bull.h"
#import "Cattle.h"
#import "MyNSobjecs.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Bull *redBull = [[Bull alloc] initWithLegsCount:4
gender:YES
eyesCount:2
masterName:@ "that cowboy"];
[redBull setSkinColor:@ "red"];
[redBull saySomething];
//legal, but not good
redBull- >masterName = @"that cowgirl";
//legal, but bad
//redBull- >eyesCount = 3;
//Trying to access a private ivar, VERY bad thing
//MyClass bullClass = redBull- >isa;
bool *redBullGender = (bool *)(redBull) + 8;
NSLog(@ "My gender is %@",*redBullGender ? @"male" : @"female");
[pool drain];
return 0;
}
第七步,选择屏幕上方菜单里面的“Run”,然后选择“Console”,打开了Console对话框之后,选择对话框上部中央的“Build and Go”,如果不出什么意外的话,那么应该出现入图7-1所示的结果。如果出现了什么意外导致错误的话,那么请仔细检查一下你的代码。如果经过仔细检查发现 还是不能执行的话,可以下载笔者为同学们准备的代码。 如果笔者的代码还是不能执行的话,请告知笔者。