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...

2 Answers 2

3

You are setting test to nil, and then sending it initWithReps:andWeight:. This is equivalent to [nil initWithReps:10 andWeight:100], which obviously isn't what you want. nil just responds to any message with itself or 0, so that init message is returning nil and sending reps to nil is returning 0.

To create an object, you want the alloc class method — i.e. Set *test = [[Set alloc] initWithReps:10 andWeight:100]. (And if you're not using ARC, you'll want to release this object when you're finished with it, per the memory management guidelines.)

Sign up to request clarification or add additional context in comments.

Comments

1

Where you're initializing your set, replace it with:

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

You're getting 0 because that's the default return from a nil object (you've initialized test to nil) - there are no NullPointerExceptions in Objective-C

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.