Nic*_*lis 6 objective-c inline-code objective-c-runtime ios
在我的应用程序中,我有一个UIViewController我用了很多UIAlertView东西给用户询问的东西.
因为我需要每个人的响应UIAlertView我已经使我的控制器成为委托UIAlertViewDelegate,这工作正常但是在UIAlertView7'si`m试图找到更好的方式来使用委托.
在java中我知道我可以为一个目的创建内联类,就像在这个问题中:Java - 内联类定义
我想知道的是:有没有办法创建一个动态委托的类?实现这样的目标
id<UIAlertViewDelegate> myCustomClass = @class {
my class code goes here
}
UIAlertView* alertView;
alertView = [[UIAlertView alloc] initWithTitle:@"Title"
message:@"Message"
delegate:myCustomClass
cancelButtonTitle:@"No"
otherButtonTitles:@"OK", @"Sure", @"Maybe", nil] ];
[alertView show];
Run Code Online (Sandbox Code Playgroud)
Ric*_*III 14
不 - Objective-C中没有"内联类".话虽如此,您可以使用objective-c在运行时创建自定义对象,这有点涉及,但我愿意分享一些代码来做你所说的.
这是一个例子:
NSObject的+ Subclass.h
#import <objc/runtime.h>
typedef struct selBlockPair { SEL aSEL; id (^__unsafe_unretained aBlock)(id, ...); } selBlockPair;
#define NIL_PAIR ((struct selBlockPair) { 0, 0 })
#define PAIR_LIST (struct selBlockPair [])
#define BLOCK_CAST (id (^)(id, ...))
@interface NSObject (subclass)
+(Class) newSubclassNamed:(NSString *) name
protocols:(Protocol **) protos
impls:(selBlockPair *) impls;
@end
Run Code Online (Sandbox Code Playgroud)
NSObject的+ Subclass.m
@implementation NSObject (subclass)
+(Class) newSubclassNamed:(NSString *)name
protocols:(Protocol **)protos
impls:(selBlockPair *)impls
{
if (name == nil)
{
// basically create a random name
name = [NSString stringWithFormat:@"%s_%i_%i", class_getName(self), arc4random(), arc4random()];
}
// allocated a new class as a subclass of self (so I could use this on a NSArray if I wanted)
Class newClass = objc_allocateClassPair(self, [name UTF8String], 0);
// add all of the protocols untill we hit null
while (protos && *protos != NULL)
{
class_addProtocol(newClass, *protos);
protos++;
}
// add all the impls till we hit null
while (impls && impls->aSEL)
{
class_addMethod(newClass, impls->aSEL, imp_implementationWithBlock(impls->aBlock), "@@:*");
impls++;
}
// register our class pair
objc_registerClassPair(newClass);
return newClass;
}
@end
Run Code Online (Sandbox Code Playgroud)
用法示例:
int main()
{
@autoreleasepool {
__strong Class newClass = [NSString newSubclassNamed:@"MyCustomString" protocols:NULL impls: PAIR_LIST {
@selector(description),
BLOCK_CAST ^id (id self) {
return @"testing";
},
NIL_PAIR
}];
NSString *someString = [newClass new];
NSLog(@"%@", someString);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
2012-10-01 10:07:33.609 TestProj[54428:303] testing