0

私はスウィズルで遊んでいますが、これを理解することはできません。私の割り当てスウィズルは次のようになります。

@interface UIAlertView (Custom)
+ (id)allocCustom;
@end

@implementation UIAlertView (Custom)    
+ (void)load
{
    Method original;
    Method mock;
    original = class_getClassMethod(self, @selector(alloc));
    mock = class_getClassMethod(self, @selector(allocCustom));
    method_exchangeImplementations(mock, original);
}

+ (id)allocCustom
{
    NSLog(@"Custom!");
    return [self allocCustom];
}    
@end

コール スタックで繰り返し呼び出される NSLog ステートメントで一時停止すると、次のように表示されます。

* thread #1: tid = 0x2c388a, 0x00003a2f My App`+[UIAlertView(self=0x03825c74, _cmd=0x0327e663) allocCustom] + 31 at MYClass.m:62, queue = 'com.apple.main-thread, stop reason = breakpoint 4.1
    frame #0: 0x00003a2f My App`+[UIAlertView(self=0x03825c74, _cmd=0x0327e663) allocCustom] + 31 at iBFGClientAppDelegate.m:62
    frame #1: 0x036c7b42 CoreFoundation`+[NSTimeZone timeZoneWithName:] + 34
    frame #2: 0x036c7a52 CoreFoundation`+[NSTimeZone systemTimeZone] + 626
    frame #3: 0x036c7767 CoreFoundation`+[NSTimeZone defaultTimeZone] + 71
    frame #4: 0x036e82cd CoreFoundation`CFTimeZoneCopyDefault + 45
    frame #5: 0x036f8b90 CoreFoundation`CFCalendarCreateWithIdentifier + 544
    frame #6: 0x03705f2c CoreFoundation`__CFLogCString + 124
    frame #7: 0x03705e6e CoreFoundation`_CFLogvEx + 270
    frame #8: 0x01581fbc Foundation`NSLogv + 137
    frame #9: 0x01581f28 Foundation`NSLog + 27
    frame #10: 0x00003a3a My App`+[UIAlertView(self=0x03825c74, _cmd=0x0327e663) allocCustom] + 42 at MYClass.m:62
    frame #11: 0x036c7b42 CoreFoundation`+[NSTimeZone timeZoneWithName:] + 34
    frame #12: 0x036c7a52 CoreFoundation`+[NSTimeZone systemTimeZone] + 626
    frame #13: 0x036c7767 CoreFoundation`+[NSTimeZone defaultTimeZone] + 71
    frame #14: 0x036e82cd CoreFoundation`CFTimeZoneCopyDefault + 45
    frame #15: 0x036f8b90 CoreFoundation`CFCalendarCreateWithIdentifier + 544
    frame #16: 0x03705f2c CoreFoundation`__CFLogCString + 124
    frame #17: 0x03705e6e CoreFoundation`_CFLogvEx + 270
    frame #18: 0x01581fbc Foundation`NSLogv + 137
    frame #19: 0x01581f28 Foundation`NSLog + 27
    frame #20: 0x00003a3a My App`+[UIAlertView(self=0x01800f3c, _cmd=0x0327e663) allocCustom] + 42 at MYClass.m:62
    frame #21: 0x023fb8ae UIKit`UIApplicationMain + 60
    frame #22: 0x0000293b My App`main(argc=1, argv=0xbfffedac) + 75 at main.m:18

timeZoneWithName: がカスタム alloc メソッドを呼び出しているようです。alloc がスウィズルされていない場合、明らかに再帰はありませんが、ここで何が起こっているのか混乱しています。

4

2 に答える 2

0

私はメソッドの入れ替えの専門家ではありませんが、あなたallocCustomはクラス メソッドであるため、self実際にはクラス自体を参照していると推測しています。あなたが本当に欲しいのはこのようなものです

+(id) allocCustom {

 id obj = calloc(class_getInstanceSize(self), 1);
 obj->isa = self;
 obj->retainCount = 1;
 return obj;
}

このリンクは役に立つかもしれません: https://www.mikeash.com/pyblog/friday-qa-2013-01-25-lets-build-nsobject.html

于 2014-02-14T19:05:54.013 に答える