解决方案
我没有区分实例变量
和实例方法
。我有点忽略了 instance variables
也可以在接口(interface)中定义的观点,这与 Java 不同 :)
#import "AnyHeaderFile.h"
@interface ClassName : SuperClass {
NSString *myVar;
}
+ (anytype)doIt;
- (anytype)doItA:(anytype)a;
@end
原始问题
我刚开始学习 ObjC,正在阅读 cheatsheet .
所以接口(interface)用{实例方法}类方法
分隔实例和类变量。所以像这样的定义应该完全无效吧?由于接口(interface)定义不需要使用 + - 将自己定义为实例和类方法?
#import "AnyHeaderFile.h"
@interface ClassName : SuperClass {
+ (anytype)doIt;
}
- (anytype)doItA:(anytype)a;
@end
在尝试编写代码之前,我会尝试弄清基本的理论基础。
最佳答案
类方法和实例方法都定义在同一个地方。 +/- 字符表示它是哪种方法。
正如评论指出的那样,大括号用于定义 ivar。所以你的界面应该是这样的:
@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];
关于ios - 实例和类方法,ObjC 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16726557/