问题
I'm creating a SQLite application, with two simple views. I have two arrays in SQLAppDelegate:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
self.modelArray = tempArray;
self.detailArray = tempArray;
[tempArray release];
So now in my implementation file I am populating "modelArray" with the contents of a SQLite table and displaying this in the first view:
+ (void) getInitialDataToDisplay:(NSString *)dbPath {
SQLAppDelegate *appDelegate = (SQLAppDelegate *)[[UIApplication sharedApplication] delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql = "select rowid as ID, ManufacturerMake as modelName from sqlitedb group by modelName";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
Model *modelObj = [[Model alloc] initWithPrimaryKey:primaryKey];
modelObj.modelName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
[appDelegate.modelArray addObject:modelObj];
[modelObj release];
}
}
}
The problem is that modelArray is being populated correctly with 114 rows, but if I do a count of detailArray after the above while statement this is also returning 114? Even though I'm not touching detailArray in the above code?
回答1:
self.modelArray = tempArray;
self.detailArray = tempArray;
Here both your instance variable arrays contain pointer to the same NSMutableArray instance (assuming that your property has retain attribute), so changes to the one of the iVars are also applied to another one (as they point to the same object).
To fix that initialize your arrays with different NSMutableArray's:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
self.modelArray = [NSMutableArray array];
self.detailArray = [NSMutableArray array];
...
回答2:
Your assigning the same NSMutableArray object to the two different variables.
What you want is to create 2 temp arrays and use them.
回答3:
What really happens is that you create an actual array in the first line, but in the next two you make modelArray
and detailArray
point to the same real in-memory array you created before. Thus, whenever you modify the first one, the second one is still pointing there and is not a separate copy.
来源:https://stackoverflow.com/questions/6170459/objective-c-appdelegate-array