IOS:在另一个类中调用一个方法 [英] IOS: call a method in another class

查看:1186
本文介绍了IOS:在另一个类中调用一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类ClassA与MethodA,我也有一个ClassB,我想从ClassB调用methodA;我写

I have a class "ClassA" with "MethodA", i have also a "ClassB" and I want to call "methodA" from "ClassB"; I write

@classA;

@property(nonatomic, retain) ClassA *classA;
//and also @synthesize...

然后我调用

[self.classA method];

但是它不调用方法....然后我在viewBind中写入classB



but it don't call the method....then I write in viewdidload in classB

self.classA = [[ClassA alloc]init];

但这个东西在ClassA中重置varaibles。

but this thing reset varaibles in ClassA.

如何解决这种情况?

推荐答案

编辑:我决定重写我的答案,因为我不认为原来是很好的措辞。

I have decided to rewrite my answer as I don't think the original was well worded.

我想你不明白Objective-C 2.0点符号是什么。这是令人困惑的,特别是如果你用C或C ++编程,因为它在句法上等同于 struct 字段或 class

I think you are failing to understand what the Objective-C 2.0 dot notation does. It is confusing, especially if you program in C or C++, as it's syntactically equivalent to the struct field or class variable access operator, but semantically different.

使用时:

self.classA = newClassA;

你实际上是这样做的:

[self setClassA: newClassA];

当定义 @property classA 使用 retain 属性,编译器生成如下的setter方法:

And when the @property classA is defined with the retain attribute, the compiler generates the setter method as something like:

- (void) setClassA:(ClassA *)newClassA
{
    if (classA != newClassA)
    {
        [newClassA retain];
        [classA release];
        classA = newClassA;
    }
}

在您给出的代码中:

[self.classA method];

实际扩展为:

[self setClassA: method];

这不是你想要的。

避免这种混淆的最简单的方法是不使用点符号,特别是在处理变量的分配或释放的同一个类的实例方法中。

The simplest way to avoid this confusion is to not use dot notation at all, and especially not within an instance method of the same class that deals with allocation or deallocation of the variable.

这篇关于IOS:在另一个类中调用一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆