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
1.1k views
in Technique[技术] by (71.8m points)

objective c - Delegate - How to Use?

I think I understand the logic behind a delegate. I got more the problem to use it. How many steps are involved? Do I have to use existing delegates? Or can I use my one ones?

In my example I got the AppDelegate that created many views (Objects / View Controllers) of the same type. Each view should somehow call a method on the AppDelegate to close itself. This would happen when a button within the view is touched. The method call would include the reference of the view (self).

So far I know from other languages responders, event listeners and so on. They are so simple to use.

Can anybody help me. I just found massive examples with a lot of code in the web. It can't be that hard to just call a parent in Objective C.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can create your own:

In MyView1.h:

@class MyView1;

@protocol MyView1Delegate <NSObject>

- (void)closeMyView1:(MyView1 *)myView1;

@end

@interface MyView1 : NSObject
{
    id<MyView1Delegate> _delegate;
}

@property (assign, nonatomic, readwrite) id<MyView1Delegate> delegate;

...

@end

In MyView1.m:

@interface MyView1

@synthesize delegate = _delegate;

...

// The method that tells the delegate to close me
- (void)closeMe
{
    ....
    if ([_delegate respondsToSelector:@selector(closeMyView1:)])
    {
        [_delegate closeMyView1:self];
    }
}

@end

In AppDelegate.h:

#import "MyView1.h"

@interface AppDelegate <MyView1Delegate>
{
    MyView1 *_myView1;
}

...

@end

In AppDelegate.m:

- (void)someCreateViewMethod
{
    _myView1 = [[MyView1 alloc] initWithFrame:NSMakeRect(0, 0, 100, 200)];
    [_myView1 setDelegate:self];
    ...
}

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

...