2011-07-25 78 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