【发布时间】:2012-02-17 00:55:31
【问题描述】:
在 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)吗?
【问题讨论】:
标签: ios cocoa-touch core-graphics