簡體   English   中英

從另一個NsMutableArray填充NSMutableArray

[英]Fill NSMutableArray from another NsMutableArray

我有兩個類indexViewControllerflashCardQuestionViewController

indexViewController我的表充滿了數組。

現在我從數據庫中獲取一些數據:

-(void)getMultipleChoiceAnswer
{   
    if(optionid!=nil)
        [optionid removeAllObjects];
    else
        optionid = [[NSMutableArray alloc] init];

    if(optionText!=nil)
        [optionText removeAllObjects];
    else
        optionText = [[NSMutableArray alloc] init];

    clsDatabase *clsDatabaseObject = [[clsDatabase alloc] init];
    sqlite3_stmt *dataRows = [clsDatabaseObject getDataset:"select optionID,OptionText from flashCardMultipleAnswer where questionId=1"];
    while(sqlite3_step(dataRows) == SQLITE_ROW)
    {
        [optionid addObject:[NSNumber numberWithInt:sqlite3_column_int(dataRows,0)]];
        [optionText addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(dataRows,1)]]; 
    }

    sqlite3_finalize(dataRows);
    [clsDatabaseObject release];
}

我在indexViewControllerviewDidLoad方法中調用此方法。

現在,我在flashCardQuestionViewController還有一個名為listNoOfOptionsInQuestion NSMutableArray

我想,以填補listNoOfOptionsInQuestion與對象optionText陣列indexViewController

我怎樣才能做到這一點?

復制數組有多種方法:可以使用-[NSArray copy]獲取不可變的副本,也可以使用-[NSArray mutableCopy]獲取可變的副本。 別忘了該副本會添加參考,因此您需要在某個地方發布或自動發布(如果您不使用GC)。

或者,您可以使用-[NSMutableArray addObjectsFromArray:]。

以您的示例為例,您似乎最終想要執行以下操作:

[flashCardQuestionViewController setListNoOfOptionsInQuestion:optionText];

然后在FlashCardQuestionViewController中,您需要類似以下內容:

- (void)setListNoOfOptionsInQuestion:(NSArray *)options
{
  if (options != listNoOfOptionsInQuestion) {
    [listNoOfOptionsInQuestion release];
    listNoOfOptionsInQuestion = [options mutableCopy];
  }
}

拉胡爾

您是否真的需要在每個對象中擁有一個完全不同的MutableArray副本。 是否可以使兩個對象都指向同一數組? 例如:

ClassOne  *one = [[ClassOne alloc] init];
ClassTwo  *two = [[ClassTwo alloc] init];

//   build mutable array mArray
//   ...

one.objectArray = mArray;
two.objectArray = mArray;

還是需要以不同的方式對兩個陣列進行更改? 嘗試一下(如上述克里斯建議):

ClassOne  *one = [[ClassOne alloc] init];
ClassTwo  *two = [[ClassTwo alloc] init];

//   build mutable array mArray
//   ...

one.objectArray = mArray;
two.objectArray = [mArray mutableCopy];

同樣,如果這不是您所需要的,那么您將不得不給我們提供一個更精確的問題,以便我們識別。

暫無
暫無

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

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