-4

私の .h ファイルには、次のものがあります。

@property (nonatomic) NSMutableArray *cards;

私の .m ファイルには、初期化子があります。

- (id) init
{
    self = [super init];
    self.cards = [NSMutableArray alloc];
    return self;
}

画面上に表示されている多数のアイテムを入力するループでは、次のようになります。

[self.cards addObject:noteView];

タッチ イベント ハンドラーには、次のようなものがあります。

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"In touchesBegan.");
    UITouch *touch = [touches anyObject];
    UIView *selectedView = nil;
    CGPoint touchLocation = [touch locationInView:self.view];

    for (UIView *card in _cards)
    {
        CGRect cardRect = [card frame];
        NSLog(@"%f", cardRect.origin.x);
        NSLog(@"%f", cardRect.origin.y);
        NSLog(@"%f", cardRect.size.height);
        NSLog(@"%f", cardRect.size.width);
        if (CGRectContainsPoint(cardRect, touchLocation)) {
            NSLog(@"Match found.");
            selectedView = card;
            CGRect selectedFrame = selectedView.frame;
            selectedFrame.origin.y = -selectedFrame.size.height;
            selectedFrame.size = selectedView.frame.size;
            float heightRatio = (float) floor([[UIScreen mainScreen] bounds].size.height + .4) / (float) selectedFrame.size.height;
            float widthRatio = (float) floor([[UIScreen mainScreen] bounds].size.width + .4) / (float) selectedFrame.size.width;
            float ratio = MIN(heightRatio, widthRatio);
            selectedFrame.size.height *= ratio;
            selectedFrame.size.width *= ratio;
            selectedFrame.origin.x = -selectedFrame.origin.x * ratio;

        }
    }
}

私が行ったすべてのタッチの出力は、無条件の NSLog ステートメントが出力されることですが、「このフロートをログに記録する」ステートメントは実行されません。NSMutableArray が正しく初期化されていないか、正しく設定されていないようです。

_cards と self.cards のどちらを参照しても同じ動作になるようです。

助けてくれてありがとう、

- 編集 -

当初考えていたものとは別のものに固執しているようです。私は今、self.cards = [[NSMutableArray alloc] init] を持っていますが、動作は同じです: ループを通過し、カードの束を取り込みますが、それらの 1 つをタップすると、タッチ ハンドラーは「In touchesBegan.」を出力します。しかし、フロートはありません。更新された init を考えると、画面上に多数のカードが表示された後、touchesBegan がカードをまったく見ていないかのように動作するのはなぜですか? (他の出力は、タッチが特定のカードのターゲットにあったかどうかに関係なく、フロートの行数を提供する必要があります。)

4

2 に答える 2

4

配列を初期化する必要があります!

self.cards = [[NSMutableArray alloc] init];

または

self.cards = [NSMutableArray new];

どちらも同等です

あなたallocがしている唯一のことは、その変数のためにメモリ内にスペースを確保することです。

アップルのドキュメントから:

alloc 
Returns a new instance of the receiving class.

init 
Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated.
于 2013-10-04T14:20:05.213 に答える
2

これにストーリーボードを使用していますか?viewDidLoad でカード プロパティを初期化してみてください。

簡単なチェックとして、オブジェクトを追加するループの直前にそのプロパティを初期化してみてください。

于 2013-10-04T14:39:48.863 に答える