0

私は独自の drawRect メソッドを定義し、4.2.1 (iOS) 5.0 (iOS) および 4.3.2 (シミュレーター) で正常に呼び出されます。しかし、3.1.3 (iPhone 2g) では呼び出されませんでした。

これにはどのような理由が考えられますか?

PS 質問を書き始めてから、3.1.3 デバイスがジェイルブレイクされていると思います。たぶん、それがこの奇妙な動作の根本的な原因です。

Upd:問題を再現するには、次のコードを使用します:

@implementation UIView (MyOwnCategory)
- (void)drawRect:(CGRect)rect
{
    const char * function = __FUNCTION__;
    [NSException raise: @"hi!" format: @"%s", function];
}
@end

[super drawRect: rect]明示的に呼び出しても3.1.3で例外は発生しませんでした

4

1 に答える 1

3

Method Swizzling について数週間前から書きたかったのですが、@Kevin Ballard のコメントがついにそれをやらせてくれました (Kevin さん、インスピレーションをありがとう)。

したがって、iOS 3.x でも機能するはずのメソッド スウィズリングを使用した問題の解決策を次に示します。

UIView+Border.h:

#import <Foundation/Foundation.h>
@interface UIView(Border)
@end

UIView+Border.m:

#import "UIView+Border.h"
#import <QuartzCore/QuartzCore.h>
#import <objc/runtime.h>

@implementation UIView(Border)

- (id)swizzled_initWithFrame:(CGRect)frame
{
    // This is the confusing part (article explains this line).
    id result = [self swizzled_initWithFrame:frame];

    // Safe guard: do we have an UIView (or something that has a layer)?
    if ([result respondsToSelector:@selector(layer)]) {
        // Get layer for this view.
        CALayer *layer = [result layer];
        // Set border on layer.
        layer.borderWidth = 2;
        layer.borderColor = [[UIColor redColor] CGColor];
    }

    // Return the modified view.
    return result;
}

- (id)swizzled_initWithCoder:(NSCoder *)aDecoder
{
    // This is the confusing part (article explains this line).
    id result = [self swizzled_initWithCoder:aDecoder];

    // Safe guard: do we have an UIView (or something that has a layer)?
    if ([result respondsToSelector:@selector(layer)]) {
        // Get layer for this view.
        CALayer *layer = [result layer];
        // Set border on layer.
        layer.borderWidth = 2;
        layer.borderColor = [[UIColor blueColor] CGColor];
    }

    // Return the modified view.
    return result;
}

+ (void)load
{
    // The "+ load" method is called once, very early in the application life-cycle.
    // It's called even before the "main" function is called. Beware: there's no
    // autorelease pool at this point, so avoid Objective-C calls.
    Method original, swizzle;

    // Get the "- (id)initWithFrame:" method.
    original = class_getInstanceMethod(self, @selector(initWithFrame:));
    // Get the "- (id)swizzled_initWithFrame:" method.
    swizzle = class_getInstanceMethod(self, @selector(swizzled_initWithFrame:));
    // Swap their implementations.
    method_exchangeImplementations(original, swizzle);

    // Get the "- (id)initWithCoder:" method.
    original = class_getInstanceMethod(self, @selector(initWithCoder:));
    // Get the "- (id)swizzled_initWithCoder:" method.
    swizzle = class_getInstanceMethod(self, @selector(swizzled_initWithCoder:));
    // Swap their implementations.
    method_exchangeImplementations(original, swizzle);
}

@end
于 2012-01-12T21:15:18.857 に答える