block 和delegate的用法

时间:2021-12-19 03:50:46
//block 和delegate的用法 设置代理
#import <UIKit/UIKit.h> typedef void (^ASIHeadersBlock)(NSString *myString); @protocol AHViewControllerDelegate <NSObject> - (void)smyheadersReceivedBlock:(NSString *)string; @end @interface AHViewController : UIViewController
{
ASIHeadersBlock headersReceivedBlock; NSObject <AHViewControllerDelegate> *delegate;
} @property (nonatomic, assign) NSObject <AHViewControllerDelegate> * delegate; - (void)setHeadersReceivedBlock:(ASIHeadersBlock)aReceivedBlock; @end --------------------------------------------------------------------- //
// AHViewController.m
// TestBlock
//
// Created by ganvin on 13-4-12.
// Copyright (c) 2013年 ganvin. All rights reserved.
// #import "AHViewController.h" @interface AHViewController () @end @implementation AHViewController
@synthesize delegate;
- (void)setHeadersReceivedBlock:(ASIHeadersBlock)aReceivedBlock
{
[headersReceivedBlock release];
headersReceivedBlock = [aReceivedBlock copy];
} - (void)viewDidLoad
{
[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.
if(headersReceivedBlock)
{
headersReceivedBlock(@"ssss");
} if (delegate!= nil && [delegate respondsToSelector:@selector(smyheadersReceivedBlock:)])
{
[delegate performSelector:@selector(smyheadersReceivedBlock:) withObject:@"sssss"];
}
} - (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc
{
delegate = nil;
if (headersReceivedBlock)
{
[headersReceivedBlock release];
headersReceivedBlock = nil;
}
[super dealloc];
}
@end