0

ARC が有効になっているため、参照が null である理由がわかりません。

私のビュー コントローラーは、ビューが読み込まれるとすぐに UIView '<strong>theGrid' をインスタンス化します。

後で、UIViewContoller メソッドを呼び出す別のクラス (MyOtherClass) 内に切り替えました - (void) updateTheGrid:(id)sender。そのメソッドは NSLog に従って呼び出されますが、UIView を出力してそこにあるかどうかを確認すると、null が返されます。

私は何を間違っていますか?ARCはなんでもついていけているなという印象でした。ViewController * vc = [[ViewController alloc] init];新しいインスタンスを作成しているように感じるので、mm "MyOtherClass" から問題が発生しているよう に感じます。しかし、その場合、古いインスタンスを参照してメソッドを呼び出すにはどうすればよいでしょうか?

NSLOG 出力

[28853:c07] Intial Grid: <GridView: 0x8e423b0; frame = (0 0; 768 1024); layer = <CALayer: 0x8e43780>>
[28853:c07] Update The Grid (null)

GridView.h

#import <UIKit/UIKit.h>

@interface GridView : UIView

- (void) gridUpdated;
@end

GridView.m

#import "GridView.h"
@implementation GridView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        NSLog(@"initWithFrame");

     }
    return self;
}

- (void)drawRect:(CGRect)rect{
   NSLog(@"Grid Draw Rect");
}

- (void) gridUpdated {
    NSLog(@"GRID VIEW.m : Grid update called");
    [self setNeedsDisplay];
}

@end

ViewController.h

#import <UIKit/UIKit.h>
#import "GridView.h"

@interface ViewController : UIViewController {
        GridView *theGrid;
}

@property (strong, retain) GridView * theGrid;
- (void) updateTheGrid : (id) sender;
@end

ViewController.m

#import "ViewController.h"
#import "GridView.h"

@interface ViewController () {}
@end

@implementation ViewController

@synthesize theGrid;

- (void)viewDidLoad {
    [super viewDidLoad];

    //draw the grid
    theGrid = [[GridView alloc] initWithFrame:self.view.frame];
    NSLog(@"Intial Grid: %@", theGrid);
    [self.view addSubview:theGrid];
}

- (void) updateTheGrid : (id) sender{
    NSLog(@"Update The Grid %@", theGrid);
    [theGrid gridUpdated];
}

@end

MyOtherClass.m

- (void) mySwitch : (id) sender {
    ViewController * vc = [[ViewController alloc] init];
    [vc updateTheGrid:sender];

}
4

1 に答える 1

2

の新しいインスタンスが作成され、保持されている以前のオブジェクトがtheGrid を含めて破棄されるためViewController、オブジェクトを再度割り当てないでください。MyOtherClass.mViewControllerViewController

ですので、の中でweakプロパティを宣言し、割り当てながら代入して ください。ViewControllerMyOtherClass.mMyOtherClass.m

例:

ViewController クラス

moc = [[MyOtherClass alloc] initWithFrame:self.view.frame];

 moc.vc = self;

MyOtherClass.h

@property(nonatomic,weak) ViewController *vc;

MyOtherClass.m

- (void) mySwitch : (id) sender {

   [self.vc updateTheGrid:sender];

}

注:前方宣言に注意してください:)

于 2013-03-14T19:33:45.880 に答える