2011-07-25 30 views
1

我只是在學習Objective C,並想知道創建和使用類的正確方法是什麼。C#和Objective C類

在C#中我可以這樣做:

Void MyMethod() 
{ 
    MyClass clsOBJ1 = new MyClass(); 
    clsOBJ1.Name = 「Fred」; 
} 

甚至

MyClass clsOBJ2; 
Void MyMethod() 
{ 
clsOBJ2 = new MyClass(); 
} 

Void MyMethod2() 
{ 
clsOBJ2.Name = 「Bob」; 
} 

你將如何實現OBJÇ類似的東西?

我在OBJÇ試過這樣:

MyClass clsOBJ3 = [[[MyClass alloc]init]autorelease]; 

但我得到錯誤信息「MYCLASS未聲明」

感謝:-)

回答

2

我需要看到更多的代碼可以肯定,但我的猜測是,你還沒有進口的標頭MyClass

在您的文件的頂部尋找:

#import "MyClass.h" 

或類似的東西

+0

這是因爲我以爲不過當我把進口線,我得到一個錯誤,說文件不能被發現。然而,它在這個項目中! – Microkid

+0

導入是一個文件的URL,所以上述導入只有在文件位於同一目錄時纔有效 – jaywayco

+0

仍然不確定它爲什麼不起作用,我刪除並重新創建了我的項目並且工作正常。多謝你們! – Microkid

1

您通常有以下幾種:

MyClass.h

@interface MyClass : NSObject { 
@private 
    // your ivars here 
} 

// your property declarations and methods here 
@end 

MyClass.m

#import "MyClass.h" 

@implementation MyClass 

// synthesize your properties here 

- (id) init { 
    if((self = [super init]) != null) { 
     // some init stuff here 
    } 

    return self; 
} 

- (void) dealloc { 
    // your class specific dealloc stuff 
    [super dealloc]; 
} 

而在一些其他的文件,你然後可以使用MyClas小號像這樣:

SomeOtherFile.m

#import "MyClass.h" 

- (MyClass *) createAMyClass { 

    MyClass * mClass = [[MyClass alloc] init]; 

    return [mClass autorelease]; 
} 
+0

您需要在SomeOtherFile.m中使用#import「MyClass.h」 – jaywayco

+0

感謝您的關注。我更新了我的代碼。 – Perception