-
使用"關(guān)聯(lián)對(duì)象"(Associated Object)存放自定義數(shù)據(jù)
可以給某對(duì)象關(guān)聯(lián)許多其它對(duì)象,這些對(duì)象通過(guò)"鍵"來(lái)區(qū)分。存儲(chǔ)對(duì)象值得時(shí)候,可以指明"存儲(chǔ)策略"(storage policy),用以維護(hù)相應(yīng)的"內(nèi)存管理語(yǔ)義"。
下列方法可以管理關(guān)聯(lián)對(duì)象:
void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy)
此方法以給定的鍵和策略為某對(duì)象設(shè)置關(guān)聯(lián)對(duì)象值。
id objc_getAssociatedObject(id object, void *key)
此方法根據(jù)給定的鍵從某對(duì)象中獲取相應(yīng)的關(guān)聯(lián)對(duì)象值。
void objc_removeAssociatedObjects(id object)
此方法移除指定對(duì)象的全部關(guān)聯(lián)對(duì)象。
-
UIAlertView的block實(shí)現(xiàn)
typedef void(^CompleteBlock) (NSInteger buttonIndex);
@interface UIAlertView (Block)
// 用Block的方式回調(diào),這時(shí)候會(huì)默認(rèn)用self作為Delegate
- (void)showAlertViewWithCompleteBlock:(CompleteBlock) block;
@end
// 需要引入#import <objc/runtime.h>頭文件
@implementation UIAlertView (Block)
static void *key = "NTOAlertView";
- (void)showAlertViewWithCompleteBlock:(CompleteBlock)block
{
if (block) {
////移除所有關(guān)聯(lián)
objc_removeAssociatedObjects(self);
objc_setAssociatedObject(self, key, block, OBJC_ASSOCIATION_COPY);
////設(shè)置delegate
self.delegate = self;
}
////show
[self show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
///獲取關(guān)聯(lián)的對(duì)象,通過(guò)關(guān)鍵字。
CompleteBlock block = objc_getAssociatedObject(self, key);
if (block) {
///block傳值
block(buttonIndex);
}
}
使用起來(lái)很簡(jiǎn)單
// 需要引入#import "UIAlertView+Block.h"頭文件
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"myself title" message:@"alert message" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil];
[alertView showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
NSLog(@"您點(diǎn)擊了%ld", buttonIndex);
}];