Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

objective c - IOS: call a method in another class

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...