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

何らかの理由で、繰り返しと重みの値が常に0に等しいため、このコードスニペットの下部にあるテストは失敗します。私はJavaのバックグラウンドから来ており、なぜそうなるのかわかりません。ばかげた質問でごめんなさい...

4

2 に答える 2

3

testnil に設定してから送信していinitWithReps:andWeight:ます。これは と同等ですが[nil initWithReps:10 andWeight:100]、これは明らかに望んでいるものではありません。nil任意のメッセージにそれ自体または 0 で応答するだけなので、init メッセージは nil を返し、nil に送信repsすると 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];

nilオブジェクトからのデフォルトの戻り値であるため、0を取得しています(テストをnilに初期化しました)-Objective-CにはNullPointerExceptionsはありません

于 2012-11-21T19:40:27.493 に答える