@interface Set : NSObject
{
// instance variables
int repetitions;
int weight;
}
// functions
- (id)init;
- (id)initWithReps: (int)newRepetitions andWeight: (int)newWeight;
@implementation Set
-(id)init
{
if (self = [super init]) {
repetitions = 0;
weight = 0;
}
return self;
}
-(id)initWithReps: (int)newRepetitions andWeight: (int)newWeight
{
if (self = [super init])
{
repetitions = newRepetitions;
weight = newWeight;
}
return self;
}
@implementation eFit2Tests
- (void)setUp
{
[super setUp];
// Set-up code here.
}
- (void)tearDown
{
// Tear-down code here.
[super tearDown];
}
- (void)testInitWithParam
{
Set* test = nil;
test = [test initWithReps:10 andWeight:100];
NSLog(@"Num Reps: %d", [test reps]);
if([test reps] != 10) {
STFail(@"Reps not currectly initialized. (initWithParam)");
}
NSLog(@"Weight: %d", [test weight]);
if([test weight] != 100) {
STFail(@"Weight not currectly initialized. (initWithParam)");
}
}
由于某些原因,此代码段底部的测试失败,因为重复和权重的值总是等于0.我来自Java的背景,并且对于为什么会这样,我一无所知。抱歉这个愚蠢的问题......
答案 0 :(得分:3)
您将test
设置为nil,然后发送initWithReps:andWeight:
。这相当于[nil initWithReps:10 andWeight:100]
,这显然不是你想要的。 nil
只响应任何带有自身或0的消息,因此init消息返回nil并且将reps
发送给nil返回0.
要创建对象,您需要alloc
类方法 - 即Set *test = [[Set alloc] initWithReps:10 andWeight:100]
。 (如果您没有使用ARC,根据内存管理指南,您将需要在完成后释放此对象。)
答案 1 :(得分:1)
如果您要初始化设置,请将其替换为:
Set *test = [[Set alloc] initWithReps: 10 andWeight: 100];
你得到0是因为它是来自nil对象的默认返回(你初始化测试为nil) - Objective-C中没有NullPointerExceptions