IOS: call a method in another class

2019-01-28 08:10发布

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...

then I call method with

[self.classA method];

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

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

but this thing reset varaibles in ClassA.

How can I solve this situation?

2条回答
Root(大扎)
2楼-- · 2019-01-28 09:03

You are creating a new instance of ClassA with the alloc and init. You need to set the property to your existing instance of classA, it is difficult to advise how without more context, but perhaps when you are creating class b, do

classB.classA = self;

This assumes that class A creates class B in the first place.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-28 09:08

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

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.

When you use:

self.classA = newClassA;

You are actually doing the same as:

[self setClassA: newClassA];

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;
    }
}

In the code you have given:

[self.classA method];

Actually expands to:

[self setClassA: method];

Which is not what you intended.

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.

查看更多
登录 后发表回答