2
@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)");
}
}

For some reason the test at the bottom of this code snippet fails because the values of repetitions and weight are always equal to 0. I come from a background in Java and am clueless as to why this is the case. Sorry for the silly question...

4

2 回答 2

3

您设置test为零,然后发送它initWithReps:andWeight:。这相当于[nil initWithReps:10 andWeight:100],这显然不是你想要的。nil只是以自身或 0 响应任何消息,因此 init 消息返回 nil,发送reps到 nil 则返回 0。

要创建一个对象,你需要alloc类方法——即Set *test = [[Set alloc] initWithReps:10 andWeight:100]. (如果您不使用 ARC,则根据内存管理指南,您需要在完成后释放该对象。)

于 2012-11-21T19:40:36.620 回答
1

在初始化集合的地方,将其替换为:

Set *test = [[Set alloc] initWithReps: 10 andWeight: 100];

你得到 0 因为这是 nil 对象的默认返回(你已经将 test 初始化为 nil)——Objective-C 中没有 NullPointerExceptions

于 2012-11-21T19:40:27.493 回答