ios - 实例和类方法,ObjC 接口(interface)

标签 ios

解决方案

我没有区分实例变量实例方法。我有点忽略了 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/

相关文章:

ios - 在Swift 2中将新字符串追加到txt文件

ios - 推送通知 -didFinishLaunchingWithOptions

ios - UIBezierPath 和渐变 iOS

ios - UIWebView 在 iOS8 中不缩放

iOS AVPlayer 不会播放有声读物,但 MPPLayerController 可以

ios - 数组索引超出范围跳过功能

ios - 滑动以删除 TableView 行

ios - 带有 UITabbar 的 UINavigationController 中的方向锁定

ios - Parse.com - 将指针从用户类设置为安装类

ios - 谷歌和 Facebook Firebase Auth 使用 swift 3