试试这个类别。您可以通过使用键将任何类型的自定义对象添加到来自 NSObject 的任何内容 - 基本上是任何类。使用该键检索对象。我想我是从stackoverflow 上的某个人(找到它)那里得到的。
标题:
//
// NSObject+arbitraryobjectonanynsobjectlol.h
//
//
// Created by someone on 2/21/14.
// Copyright (c) 2014 someone. All rights reserved.
//
#import <Foundation/Foundation.h>
// https://stackoverflow.com/a/10319083/129202
@interface NSObject (arbitraryobjectonanynsobjectlol)
- (id)associativeObjectForKey: (NSString *)key;
- (void)setAssociativeObject: (id)object forKey: (NSString *)key;
@end
和实施:
//
// NSObject+arbitraryobjectonanynsobjectlol.m
// someone
//
// Created by someone on 2/21/14.
// Copyright (c) 2014 someone. All rights reserved.
//
#import "NSObject+arbitraryobjectonanynsobjectlol.h"
#import <objc/runtime.h>
@implementation NSObject (arbitraryobjectonanynsobjectlol)
static char associativeObjectsKey;
- (id)associativeObjectForKey: (NSString *)key {
NSMutableDictionary *dict = objc_getAssociatedObject(self, &associativeObjectsKey);
return [dict objectForKey: key];
}
- (void)setAssociativeObject: (id)object forKey: (NSString *)key {
NSMutableDictionary *dict = objc_getAssociatedObject(self, &associativeObjectsKey);
if (!dict) {
dict = [[NSMutableDictionary alloc] init];
objc_setAssociatedObject(self, &associativeObjectsKey, dict, OBJC_ASSOCIATION_RETAIN);
} [dict setObject: object forKey: key];
}
@end