0

In View Controller.m

@interface ViewController ()
{
    CustomView *view;
}

@implementation ViewController

-(void)viewDidLoad {
    [super viewDidLoad];

    view = nil;
    view = [[CustomView alloc]init];

    [self.view addSubview:view];
}

CustomView.m 内

-(CustomView *)init
{
    CustomView *result = nil;
    result = [[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil] objectAtIndex:0];

    return result;
}

カスタム ビューに 2 つのボタンがあります。カスタム ビューは正常に読み込まれましたが、CustomView.m ファイルで ARC を有効にするとボタン アクションが起動しません。ARC を無効にすると、ボタン アクションが起動します…</p>

どこが間違っているのか..

それはuiviewのペン先をロードする正しい方法ですか(プロジェクトの多くの場所で使用したい..)

ありがとうございました ..

4

1 に答える 1

0

これは、initメソッドの非常に紛らわしい/混乱した実装です。

- (CustomView *)init
{
    CustomView *result = nil;
    result = [[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil] objectAtIndex:0];

    return result;
}

こんな感じに変えるといいのですが…

// class method not instance method
+ (CustomView *)loadFromNib {
    return [[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil] objectAtIndex:0];
}

次に、ViewControllerメソッドを次のように変更します...

@interface ViewController ()

@property (nonatomic, strong) CustomView *customView; // don't call it view, it's confusing

@end

@implementation ViewController

-(void)viewDidLoad {
    [super viewDidLoad];

    self.customView = [CustomView loadFromNib];

    [self.view addSubview:self.customView];
}

あなたが抱えている問題は、インスタンス メソッドとして init メソッドを実装したが、インスタンスを無視して新しいインスタンスを返したことが原因である可能性があります。

そのメモリへの影響は混乱を招き、解決するのが困難です。

于 2016-01-21T10:44:01.600 に答える