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

标签 ios objective-c

我正在开发一个 Objective-C 框架,供其他开发人员使用。

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

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

if (NSClassFromString(@"ASIdentifierManager")) {
        NSString adString = [[[NSClassFromString(@"ASIdentifierManager") sharedManager] advertisingIdentifier] UUIDString];
}

但是现在,我想让我的框架的公共(public)函数的参数包含可选依赖项的类,但我无法做到这一点。

例如:

我想要一个函数:

+ (void) sendLocation: (CLLocation *) myLoc;

但 CoreLocation.framework 将被选择性地链接并且可能不适用于应用程序。我如何才能对上述 AdSupport.framework 采用类似的方法?

我以为我可以做这样的事情:

+ (void) sendLocation: (NSClassFromString(@"CLLocation") *) myLoc; 

+ (void) sendLocation: (id) myLoc; 

+ (void) sendLocation: (Class) myLoc; 

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

有人可以帮忙吗?

最佳答案

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

标题:

@class MKMapView;
@interface MyTestInterface : NSObject
+ (void)printMapViewDescription:(MKMapView *)mapView;
@end

执行文件:

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

@implementation

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

@end

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

编辑:

NSInvocation 示例

标题:

@class MKMapView;
@interface MyTestInterface : NSObject
+ (void)printMapViewFrame:(MKMapView *)mapView;
@end

执行文件:

#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

关于ios - 如何在 objective-c 框架函数中将可选依赖项的参数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36182587/

相关文章:

ios - 调用 imageWithContentsOfFile 后 UIImage 为空

ios - 正确的scrollViewWillEndDragging代码?

ios - 如何在第一次构建期间使用变量设置标签的初始值?

iphone - 如何在 iPhone/IOS 应用程序中以编程方式更改圆形按钮图像的颜色?

iphone - 如何限制 NSFetchRequest 的结果数?

ios - 如何动态创建多个 NSMutableArray(s)?

ios - UICollectionView 中的高内存使用率

objective-c - 为什么 Objective-C 对象在释放后仍然存在?

ios - UITableView中的多线程

iphone - 连接到 Windows Live Messenger 网络时出现不可能的问题