如何在目标c框架函数中将可选依赖项的参数作为参数传递

and*_*asv 5 objective-c ios

我正在开发一个目标c框架供其他开发人员使用.

在这个框架中,我想使用其他框架中的可用类(如果它们可用).

例如,目前我正在使用AdSupport.framework(如果可用 - 由应用程序开发人员链接),采用以下方法:

if (NSClassFromString(@"ASIdentifierManager")) {
        NSString adString = [[[NSClassFromString(@"ASIdentifierManager") sharedManager] advertisingIdentifier] UUIDString];
}
Run Code Online (Sandbox Code Playgroud)

但是现在,我希望我的框架的公共函数的参数包含可选依赖项的类,我无法做到这一点.

例如:

我想要一个功能:

+ (void) sendLocation: (CLLocation *) myLoc;
Run Code Online (Sandbox Code Playgroud)

但CoreLocation.framework可以选择性地链接,也许不适用于应用程序.如何使用上述AdSupport.framework的类似方法?

我以为我可以这样做:

+ (void) sendLocation: (NSClassFromString(@"CLLocation") *) myLoc; 
Run Code Online (Sandbox Code Playgroud)

要么

+ (void) sendLocation: (id) myLoc; 
Run Code Online (Sandbox Code Playgroud)

要么

+ (void) sendLocation: (Class) myLoc; 
Run Code Online (Sandbox Code Playgroud)

然后以某种方式提取坐标,但无法实现.最后一个选项(Class)似乎编译但我找不到提取params的方法..

任何人都可以帮忙吗?

Jon*_*hon 0

MapKit 的简短示例(除非您请求,否则不会链接到您的应用程序)

标题:

@class MKMapView;
@interface MyTestInterface : NSObject
+ (void)printMapViewDescription:(MKMapView *)mapView;
@end
Run Code Online (Sandbox Code Playgroud)

实施文件:

#import "MyTestInterface.h"
#import <MapKit/MapKit.h>

@implementation

+ (void)printMapViewDescription:(MKMapView *)mapView {
    if ((NSClassFromString(@"MKMapView")) {
       NSLog(@"%@", mapView);
    } else {
       NSLog(@"MapKit not available");
    }
}

@end
Run Code Online (Sandbox Code Playgroud)

所以你链接到内部标题。仅当您提供二进制文件或仅使用苹果框架时,这才有效。如果您提供源代码并且想要与第三方框架交互,则必须在匿名对象 (id) 上使用performSelector、NSInitation 或 objc-runtime。

编辑:

NSInspiration 示例

标题:

@class MKMapView;
@interface MyTestInterface : NSObject
+ (void)printMapViewFrame:(MKMapView *)mapView;
@end
Run Code Online (Sandbox Code Playgroud)

实施文件:

#import "MyTestInterface.h"

@implementation

+ (void) printMapViewFrame:(id)mapView {
    if ([mapView respondsToSelector:@selector(frame)]) {
        NSMethodSignature *sig = [mapView methodSignatureForSelector:@selector(frame)];
        if (sig) {
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
            [invocation setTarget: mapView];
            [invocation setSelector:@selector(frame)];
            [invocation invoke];
            CGRect rect;
            [invocation getReturnValue:&rect];
            NSLog(@"%@", NSStringFromCGRect(rect));
        }
    }
}

@end
Run Code Online (Sandbox Code Playgroud)