Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 11th, 2012  |  syntax: None  |  size: 1.12 KB  |  hits: 5  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #import <Foundation/Foundation.h>
  2. #import <stdio.h>
  3.  
  4. @interface Hoge : NSObject
  5. {
  6.     id object;
  7. }
  8. - (id)init;
  9. - (void)replaceSelf;
  10.  
  11. @property (readonly) id object;
  12. @end
  13.  
  14. @implementation Hoge
  15. @synthesize object;
  16. - (id)init
  17. {
  18.     self = [super init];
  19.     if (self)
  20.     {
  21.         object = [[NSObject alloc] init];
  22.     }
  23.     return self;
  24. }
  25. - (void)replaceSelf
  26. {
  27.     self = [self init]; // init以外のインスタンスメソッドでselfを上書きする
  28. }
  29. - (void)dealloc
  30. {
  31.     [object release];
  32.     [super dealloc];
  33. }
  34. @end
  35.  
  36. int main()
  37. {
  38.     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  39.  
  40.     Hoge *hoge = [[Hoge alloc] init];
  41.     NSLog(@"%@ -- %@", hoge.description, hoge.object);
  42.  
  43.     [hoge replaceSelf];
  44.     NSLog(@"%@ -- %@", hoge.description, hoge.object);
  45.  
  46.     [hoge release];
  47.     [pool release];
  48.  
  49.     getchar();
  50.  
  51.     return 0;
  52. }
  53.  
  54. // 実行すると↓みたいな感じになる.
  55. // hoge.objectがメモリリークしそうな気がするけど…
  56.  
  57. // 2012-03-19 21:18:17.558 hoge[18860:707] <Hoge: 0x101314520> -- <NSObject: 0x101314590>
  58. // 2012-03-19 21:18:17.563 hoge[18860:707] <Hoge: 0x101314520> -- <NSObject: 0x7ff20a500170>