2011-11-11 18 views
0

我想獲得此代碼工作,但似乎無法獲得,顯示了變量被設置任何輸出:Objective-C中不能設置類/對象變量

#import <Foundation/Foundation.h> 
#import "thingy.h" 

int main (int argc, const char * argv[]) 
{ 

@autoreleasepool { 

thingy *mythingy; 

    [mythingy setMass:75.00]; 
    [mythingy setTime:5.00]; 

    NSLog(@"mass of mythingy = %f kg", [mythingy mass]); 
    NSLog(@"time of mythingy = %f sec", [mythingy time]); 

    } 
return 0; 
} 

這是我得到的輸出:

mass of mythingy = 0.000000 kg 
time of mythingy = 0.000000 sec 

我也嘗試不使用@autoreleasepool(ARC),代碼如下所示但具有相同的輸出前:

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
    thingy *mythingy; 

    [mythingy setMass:75.00]; 
    [mythingy setTime:5.00]; 

    NSLog(@"mass of mythingy = %f kg", [mythingy mass]); 
    NSLog(@"time of mythingy = %f sec", [mythingy time]); 

[mythingy release]; 
[pool drain]; 

更新:

好吧,所以我採取了以前的代碼,並增加了一條線現在看起來像這樣,但工作,但令人沮喪,因爲我想使用ARC !!!!

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
thingy *mythingy = [[thingy alloc]init]; 

    [mythingy setMass:75.00]; 
    [mythingy setTime:5.00]; 

    NSLog(@"mass of mythingy = %f kg", [mythingy mass]); 
    NSLog(@"time of mythingy = %f sec", [mythingy time]); 

[mythingy release]; 
[pool drain]; 

輸出這個代碼:

mass of mythingy = 75.000000 kg 
time of mythingy = 5.000000 sec 

回答

5

你必須創建一個對象(mythingy),然後才能使用它。嘗試將thingy *mythingy;更改爲thingy *mythingy = [mythingy new];或者使用自定義方法對其進行初始化(如果已實施)。

+0

是的,它現在可以工作,tottally工程,但我希望能夠使用新的自動引用計數,我似乎無法找到任何有關該主題的好資源,以便@autoreleasepool可以使用和內存管理可以被忽略(對於簡單的項目) – Moose

+0

這應該是另一個問題。在這裏回答會讓它脫離主題。 (有些東西讓你去:http://stackoverflow.com/questions/6385212/how-does-the-new-automatic-reference-counting-mechanism-work)另外,如果它的工作,然後接受兩個答案之一。 – Jef

+1

@Mooseman - 這與ARC無關 - 你需要分配和初始化你的對象。 ARC不會爲您初始化對象。 – jrturton

2

你在哪裏分配啄?
你需要像

mythingy = [[thingy alloc] init]; 
// or 
mythingy = [thingy new];