У меня есть класс, я хочу, чтобы какой-то метод передачи объекта массива

Как сказано в заголовке: у меня есть ObjcClass, который я хочу использовать повторно, потому что класс-(void)test1:xxx -(void)test2:xxx argu:yyyЯ не хочу этого делать

[dispatchArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
      [obj test2:xxx argu:yyy];
 }];

пример:

 - (void)test:(NSString *)argument1 {
    NSArray *dispatchArray = @[];//If the array is initialized with multiple objects
//I want each object to call the "test:" method unlike the following
//    [dispatchArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//        [obj performSelector:@selector(test:) withObject:argument1];
//        // or [obj test:argument1];
//    }];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [_services enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL * stop) {
        if ([obj respondsToSelector:_cmd]) {
            [obj application:application didFinishLaunchingWithOptions:launchOptions];
        }
    }];

    return YES;
}

как это ,UIApplicationDelegate имеет ряд методов , Я не хочу писать [obj application:application didFinishLaunchingWithOptions:launchOptions]; или [obj applicationWillResignActive:application]; напротив, я надеюсь, что такой метод, как [obj responsedsToSelector: _cmd] ,, который я могу предложить в качестве общего метода, например [obj invokeWithMethod:_cmd arguments:_VA_LIST]; Могут ли эти методы быть оптимизированы, потому что они делают то же самое с другим методом

2 ответа

Решение

Методы, которые вы делегировали приложению, были реализованы, вы должны реализовать их как раньше. К методу в UIApplicationDelegate Протокол, который не реализован вашим делегатом приложения, вы можете использовать пересылку сообщений для достижения вашей цели. Переопределите методы пересылки сообщений вашего делегата приложения, как показано ниже:

- (BOOL)respondsToSelector:(SEL)aSelector {
    struct objc_method_description desc = protocol_getMethodDescription(objc_getProtocol("UIApplicationDelegate"), aSelector, NO, YES);
    if (desc.name != nil) {
        return YES;
    }
    return [super respondsToSelector:aSelector];
}

- (void)forwardInvocation:(NSInvocation *)anInvocation {
    SEL selector = [anInvocation selector];
    struct objc_method_description desc = protocol_getMethodDescription(objc_getProtocol("UIApplicationDelegate"), selector, NO, YES);
    if (desc.name != nil) {
        [_services enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj respondsToSelector:selector]) {
                [anInvocation invokeWithTarget:obj];
            }
        }];
    }
}

Получить возвращаемые значения:

NSMutableArray *returnValues = [NSMutableArray array];
[_services enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    id returnValue = [NSNull null];
    if ([obj respondsToSelector:selector]) {
        [anInvocation invokeWithTarget:obj];

        const char *returnType = anInvocation.methodSignature.methodReturnType;

        if( !strcmp(returnType, @encode(void)) ){
            //If the return value is `void`, just set returnValue = [NSNull null]
        } else if( !strcmp(returnType, @encode(id)) ){
            // if the return type is derived data types(`id`)
            [anInvocation getReturnValue:&returnValue];
        }else{
            //if the return value is basicdata type
            NSUInteger length = [anInvocation.methodSignature methodReturnLength];
            void *buffer = (void *)malloc(length);
            [anInvocation getReturnValue:buffer];
            if( !strcmp(returnType, @encode(BOOL)) ) {
                returnValue = [NSNumber numberWithBool:*((BOOL*)buffer)];  
            } else if( !strcmp(returnType, @encode(NSInteger)) ){
                returnValue = [NSNumber numberWithInteger:*((NSInteger*)buffer)];  
            }  
            returnValue = [NSValue valueWithBytes:buffer objCType:returnType];
        }
    }
    // If the `obj` can not responds to selector, or the return value is void(nil), we set the `returnValue = [NSNull null]`
    [returnValues addObject:returnValue];
}]

Похоже, вы просто хотите пройтись по объектам в массиве. Это не очень безопасный тип. Все объекты должны предоставлять "тестовый" метод. Если они все одного и того же класса, это было бы лучше, чем использование NSObject.

for (NSObject *obj in dispatchArray) {
        [obj performSelector:@selector(test:) withObject:argument1];
}
Другие вопросы по тегам