C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在objective-c中创建自定义动态类大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的应用程序中,我有一个UIViewController,我使用了很多UIAlertView向用户提问.

因为我需要每个UIAlertView的响应我已经使我的控制器成为UIAlertViewDelegate的委托,这工作正常,但在7 UIAlertView之后,我试图找到一种更好的方式来使用委托.

java中,我知道我可以为单个目的创建内联类,例如在这个问题中:Java – inline class definition

我想知道的是:有没有办法创建一个动态委托的类?实现这样的目标

id<UIAlertViewDelegate> myCustomcatlass = @class {
    my class code goes here
}

UIAlertView* alertView;
alertView = [[UIAlertView alloc] initWithtitle:@"title"
                                       message:@"message"
                                      delegate:myCustomcatlass
                             cancelButtontitle:@"No"
                             otherButtontitles:@"OK",@"Sure",@"Maybe",nil] ];    
[alertView show];

解决方法

不 – 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

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

用法例:

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);
    }
}

输出

2012-10-01 10:07:33.609 TestProj[54428:303] tesTing

大佬总结

以上是大佬教程为你收集整理的在objective-c中创建自定义动态类全部内容,希望文章能够帮你解决在objective-c中创建自定义动态类所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。