2012-11-21 34 views
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和我無言以對至於爲什麼是這樣。很抱歉的愚蠢的問題...Objective-C的初始化函數沒有正確

回答

1

當你初始化你的設置,將其替換爲:

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

你得到0,因爲這是從零對象的默認回報(已初始化,測試爲零) - Objective-C中沒有NullPointerExceptions

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,當你完成它的時候,你需要按照內存管理指南發佈這個對象。)

+0

非常感謝! –