簡體   English   中英

添加 object 后 NSMutableArray 的計數為 0

[英]Count of NSMutableArray is 0 after adding object

嗨,我有一個帶有兩個實例變量 NSString 和 NSDate 的 object (objectA)。 我還有另外兩個對象,一個帶有 tableView 和添加按鈕 (objectB),一個在您按下添加按鈕 (objectC) 時以模態方式呈現,在此 object 視圖中您可以輸入名稱和日期,當此 object (objectC) 關閉時,我創建新的object (objectA) 帶有名稱和日期。

objectB 有 NSMutableArray,我想將 objectA 添加到這個數組中,這樣它就可以出現在 tableView 中,我在 objectC.m 中這樣做

- (IBAction)saveButtonPressed {
   objectA *a = [[objectA alloc] init];
   [a setName:[myUITextField text]];
   [a setDate:[myDatePicker date]];

   objectB *b = [[objectB alloc] init];
   [[b myMutableArray] addObject:a]];
   [[b myMutableArray] count]; // count == 1 here but when i go back to objectB implementation it will be 0

}

和應用程序在這里崩潰

有任何想法嗎?

謝謝,

編輯:崩潰消失了我只是編輯了 objectA 的 init 方法,但 myMutableArray 仍然是 0

在對象B.m

- (id)initWithStyle:(UITableViewStyle)style {
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {

        UIBarButtonItem *bbi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                                             target:self 
                                                                             action:@selector(addBarButton:)];
        [navItem setRightBarButtonItem:bbi];
        [bbi release];

        myMutableArray = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)addBarButton:(id)sender {
    myObjectC = [[objectC alloc] init];
    [self presentModalViewController:myObjectC animated:YES];

}

我也有objectB.h

@property (nonatomic, retain) NSMutableArray *myMutableArray;

saveButtonPressed 方法中 objectC 中 myMutableArray 的計數現在為 1,但是當我返回要顯示 myMutableArray 的 objectB tableView 時,仍然為 0

Edit2:在我放了很多 NSLog 之后,我發現當我在 saveButtonPressed: 方法中創建新 objectB 時,myMutableArray 的計數將為 1,但是當我 go 回到我的 tableView (objectB) myMutableArray 時,可能是因為我創建了新的並且在 objectC 中分離 objectB 的 object (saveButtonPressed:) 如果我不分配並在 saveButtonPressed 中初始化 objectB:方法 objectB 將為零,我不能將 objectA 放入 myMutableArray

所以我想我必須獲得指向原始 objectB 的指針,但如何?

由於在添加 object 之后 count == 0,我猜這是兩件事之一:

  1. [b myMutableArray]返回 nil,因為您忘記在 objectB 的 init function 中分配 myMutableArray(例如myMutableArray = [[NSMutableArray alloc] initWithCapacity:10];

  2. [b myMutableArray]每次調用時都會返回一個新的可變數組。 也許你正在做類似的事情:

- (NSMutableArray *)myMutableArray {
  return [NSMutableArray arrayWithCapacity:10];
}

聽起來(1)可能是可能的原因,但它仍然不能解釋崩潰。 發生崩潰時,您在調試控制台中看到了哪些錯誤消息?

暫無
暫無

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

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