簡體   English   中英

無法使addObject在NSMutableArray上工作

[英]Can't get addObject to work on NSMutableArray

我正在嘗試將UIButton對象添加到數組中,但這樣做失敗。 每當我調用[pixels count]或[colors count]時,它都會返回0。我嘗試使用[self.arrayName addObject:myObject]和[arrayName addObject:myObject],但似乎都不起作用。 我對Objective-C還是很陌生,所以對我來說似乎很愚蠢,但這已經讓我感到沮喪了一個多小時。

這是ViewController.h的代碼

 #import <UIKit/UIKit.h>

 @interface ViewController : UIViewController {
 NSMutableArray *pixels;
 NSMutableArray *colors;
 }
 @property (nonatomic, retain) NSMutableArray *pixels;
 @property (nonatomic, retain) NSMutableArray *colors;
 @end

這是ViewController.m中的相關代碼

 int x = 30;
 int y = 60;
 for(int i=0; i<10; i++ ) {
      UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
      [self.pixels addObject:button];
      x += 20;
      y += 20;
 }

我已經壓縮了整個項目,可以在這里下載: http : //mdl.fm/pixelated.zip

在此先感謝任何可以提供幫助的人!

在嘗試使用數組之前,請嘗試添加以下內容:

NSMutableArray *pixels = [[NSMutableArray alloc] init];

Obj-C中的數組在使用之前需要初始化。 由於在nil實例上調用方法僅在Obj-C中返回零,因此很容易做到這一點,並且直到數組沒有存儲您認為應該的內容時才注意到。

編輯以添加評論中的信息:

您可以將初始化放入-ViewDidLoad方法中,以便一旦ViewController本身准備好就可以進行初始化。 確保retain它們,以免它們被自動垃圾收集。

您使用init方法初始化了像素-在情節提要中設置的控制器不會調用init。 可以將其更改為initWithCoder:,或者將數組初始化移動到viewDidLoad。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM