gpt4 book ai didi

ios - CGPathRef 与 CGMutablePathRef

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:17:06 29 4
gpt4 key购买 nike

在 iOS 中,有两个 C 结构表示描述可绘制形状的路径:CGPathRef 和 CGMutablePathRef。从他们的名字看来,CGPathRef 指的是一旦创建就不能更改的路径,而 CGMutablePathRef 指的是可修改的路径。然而,事实证明,CGPathRef 可以传递给需要 CGMutablePathRef 的函数,在我看来唯一的区别是前者会在传递给它的函数修改路径时生成警告,而后者不会吨。例如下面的程序:

#import <UIKit/UIKit.h>

@interface TestView : UIView {
CGPathRef immutablePath;
CGMutablePathRef mutablePath;
}
@end
@implementation TestView

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
mutablePath = CGPathCreateMutable();
immutablePath = CGPathCreateCopy(mutablePath); // actually you might just do "immutablePath = CGPathCreateMutable();" here - The compiler doesn't even complain

self.backgroundColor = [UIColor whiteColor];
}

return self;
}


- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touchesBegan executed!");
[self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddPath(context, immutablePath);
CGPathAddRect(immutablePath, NULL, CGRectMake(100.0, 100.0, 200.0, 200.0)); // generates a warning specified later
CGContextFillPath(context);
}


@end


@interface TestViewController : UIViewController
@end

@implementation TestViewController

@end

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

@implementation AppDelegate

@synthesize window = _window;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];

// Instantiate view controller:
TestViewController *vc = [[TestViewController alloc] init];
vc.view = [[TestView alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.window.rootViewController = vc;
[self.window makeKeyAndVisible];
return YES;
}
@end


int main(int argc, char *argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, @"AppDelegate");
}
}

这是编译器给出的警告:将“CGPathRef”(又名“const struct CGPath *”)传递给“CGMutablePathRef”(又名“struct CGPath *”)类型的参数会丢弃限定符

也许我忽略了这里的重点,但这两者之间是否还有其他区别,除了提醒程序员他可能不打算修改(由 CGPathRef 引用的)路径?

最佳答案

在 C 语言中,将错误的类型传递给函数是可能的,但这几乎总是不是一个好主意。即使从技术上讲它们似乎被定义为同一事物,Apple 也可能有充分的理由将它们作为不同的事物。很可能是为了让代码更具可读性和可理解性,或者 Apple 计划稍后进行更改。

毕竟,跳转到定义揭示了真正的区别:

typedef struct CGPath *CGMutablePathRef;
typedef const struct CGPath *CGPathRef;

CGPathRef 是一个 const typedef(如果您不太确定它的作用,请谷歌它)。但是 C 允许您打破 const 定义,这就是为什么您仍然能够将 CGPathRef 传递给需要 CGMutablePathRef 的函数并对其进行适当修改的原因。它还解释了为什么会抛出 discards qualifiers 警告。

关于ios - CGPathRef 与 CGMutablePathRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9321462/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com