Objective c 如何使类对象自动显示行为

Objective c 如何使类对象自动显示行为,objective-c,cocoa-touch,Objective C,Cocoa Touch,我很难理解编写和调用类的更好点。可能是 在Swift中更容易掌握,但在没有学习的情况下开始这项研究让我感到困扰 首先在obj_c中正确处理它。目前我做的每件事都是 带有IVAR和全局视图的视图控制器。在应用程序中使用两个应用程序18个月 储存过期未付的物品,以纠正错误 我已经形成了一个概念,即属性是对象的状态,任何方法 在内部,我们可以确定物体的行为,但到目前为止还没有人能告诉我 下面是一个典型的类标题: @interface Math : NSObject @property (nonato

我很难理解编写和调用类的更好点。可能是 在Swift中更容易掌握,但在没有学习的情况下开始这项研究让我感到困扰 首先在obj_c中正确处理它。目前我做的每件事都是 带有IVAR和全局视图的视图控制器。在应用程序中使用两个应用程序18个月 储存过期未付的物品,以纠正错误

我已经形成了一个概念,即属性是对象的状态,任何方法 在内部,我们可以确定物体的行为,但到目前为止还没有人能告诉我

下面是一个典型的类标题:

@interface Math : NSObject

@property (nonatomic, assign) int a;
@property (nonatomic, assign) int b;
@property (nonatomic, assign) int c;

-(int)mathemagic:(int)a adding:(int)b;

@end
以及相应的类实现:

@implementation Math

@synthesize a = _a;
@synthesize b = _b;
@synthesize c = _c;

- (instancetype)init {
    self = [super init];
    if (self) {
       _a = 0;
       _b = 0;
       _c = 0;
    }
    return self;
}

-(int)mathemagic:(int)a adding:(int)b {
    _c = (a + b);
    return _c;
}

@end
最后在我的ViewController中的适当位置

#import "Math"

- (void)viewDidLoad {

    [super viewDidLoad];

    Math *theMath = [Math alloc]; // makes no difference if I init[]

    theMath.a = 10;
    theMath.b = 20;
    NSLog (@" answer is %i",theMath.c);
    // but still outputs to:
    // answer is 0
 }
现在我知道你可以做一个iVar然后这样做

int d = [self.theMath mathemagic:theMath.a adding:theMath.b];
NSLog (@" sum: %i",d);
但我不该这么做。Stanford CS193P似乎总是将类作为ViewController的属性,但随后所有内容都再次表示为self.theMath.which,并且数据模型不再封装在VC之外?也许斯坦福大学会把高级分心留给Java毕业生,直到后来

对于这个读过大卫·弗拉纳根的《简而言之的Java》的人来说, 还有Niemeyer Knudsen的“学习Java”,现在是晚些时候了

我不必去碰Math.c,只要给[theMath.a]和[theMath.b]赋值就足够了


我哪里错了?

我想这是因为您在alloc init中设置了a和b=0。而且您没有在任何地方调用
[self mathemagic:a adding:b]

我想我是Math.m你应该把
-(instancetype)init
改为

    - (instancetype)initWith:(int)a andb:(int)b {
self = [super init];
if (self) {
    _c = [self mathemagic:a adding:b];
}
return self;
}

并在
viewDidLoad
中使用

     Math *theMath = [[Math alloc]initWith:10 andb:20];

希望这有帮助:)

我认为您对Objective-C类的工作方式有误解

首先,在Objective-C中创建对象需要两个步骤。您必须同时执行以下两个步骤:

  • 为新对象动态分配内存
  • 将新分配的内存初始化为适当的值
因此,您的数学实例初始化应该如下所示:

Math *theMath = [[Math alloc] init];
只需调用
alloc
即可将对象的所有实例变量归零。虽然在您的情况下,使用
[Math alloc]
[[Math alloc]init]
没有什么区别,但这不是一种好的编程风格

其次,如果“自动显示行为”是指记录
mathemagic:adding:
method的结果,那么应该将其作为参数传递给
NSLog
函数,而不是
math.c

NSLog(@" should show the sum being %i", [theMath mathemagic:theMath.a adding:theMath.b]);