实例和类方法,ObjC接口

时间:2013-05-24 01:51:41

标签: ios

解决方案

我没有区分instance variablesinstance methods。我有点错过了instance variables也可以在接口中定义的点,与Java不同:)

#import "AnyHeaderFile.h"
@interface ClassName : SuperClass {
    NSString *myVar;
}
+ (anytype)doIt;
- (anytype)doItA:(anytype)a;
@end

原始问题

我刚开始学习ObjC并正在阅读cheatsheet

因此,接口将实例和类变量与{ instance methods } class methods分开。那么这样的定义应该完全无效吧?由于接口定义不需要使用+ - 来将自己定义为实例和类方法吗?

#import "AnyHeaderFile.h"
@interface ClassName : SuperClass {
    + (anytype)doIt;
}
- (anytype)doItA:(anytype)a;
@end

在我尝试编写代码之前,我试图让理论的基本原理正确。

2 个答案:

答案 0 :(得分:2)

如果您想要静态方法,请尝试以下代码:

#import "AnyHeaderFile.h"
@interface ClassName : SuperClass
   + (id)instance;
@end
@implementation ClassName
static id _instance;
+ (id)instance {
   if (!_instance) {
      _instance = [[SomeClass alloc] init];
   }
   return _instance;
}
//...
@end

答案 1 :(得分:2)

类方法和实例方法都在同一个地方定义。 +/-字符表示它是什么类型的方法。

正如评论所指出的那样,大括号用于定义ivars。所以你的界面应该是这样的:

@interface ClassName : SuperClass  
{
    //Define your ivars here. 

    //Remember that in object oriented programming a class will have instance variables 
    //and methods. (In obj-c ivars can also be exposed as properties, which is a way of 
    //wrapping the access in a (perhaps auto-generated) method.)

    //ivars defined in the header can be accessed 
    //by subclasses - default 'protected' scope. 
}

+ (anytype)doIt;
- (anytype)doItA:(anytype)a;

@end

要调用类方法:

//This sends a message to the ClassName singleton object. 
[ClassName doIt]; 

要调用实例方法:

ClassName instance = [ClassName alloc] init];
//This sends a message to the instance of a class defined by ClassName
[instance doItA:someArgument];