Created
March 19, 2012 12:21
-
-
Save st63jun/2109934 to your computer and use it in GitHub Desktop.
Objective-Cで,selfを上書きするとどうなるの
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
#import <stdio.h> | |
@interface Hoge : NSObject | |
{ | |
id object; | |
} | |
- (id)init; | |
- (void)replaceSelf; | |
@property (readonly) id object; | |
@end | |
@implementation Hoge | |
@synthesize object; | |
- (id)init | |
{ | |
self = [super init]; | |
if (self) | |
{ | |
object = [[NSObject alloc] init]; | |
} | |
return self; | |
} | |
- (void)replaceSelf | |
{ | |
self = [self init]; // init以外のインスタンスメソッドでselfを上書きする | |
} | |
- (void)dealloc | |
{ | |
[object release]; | |
[super dealloc]; | |
} | |
@end | |
int main() | |
{ | |
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; | |
Hoge *hoge = [[Hoge alloc] init]; | |
NSLog(@"%@ -- %@", hoge.description, hoge.object); | |
[hoge replaceSelf]; | |
NSLog(@"%@ -- %@", hoge.description, hoge.object); | |
[hoge release]; | |
[pool release]; | |
getchar(); | |
return 0; | |
} | |
// 実行すると↓みたいな感じになる. | |
// hoge.objectがメモリリークしそうな気がするけど… | |
// 2012-03-19 21:18:17.558 hoge[18860:707] <Hoge: 0x101314520> -- <NSObject: 0x101314590> | |
// 2012-03-19 21:18:17.563 hoge[18860:707] <Hoge: 0x101314520> -- <NSObject: 0x7ff20a500170> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment