问题描述
我正在创建一个带有两个简单视图的SQLite应用程序.我在SQLAppDelegate中有两个数组:
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];
所以现在在我的实现文件中,我用SQLite表的内容填充"modelArray",并在第一个视图中显示它:
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];
}
}
}
问题是modelArray正确填充了114行,但是如果在上述while语句之后对 detailArray 进行计数,这是否也返回114?即使我没有在上面的代码中触摸detailArray?
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?
推荐答案
self.modelArray = tempArray;
self.detailArray = tempArray;
这两个实例变量数组都包含指向同一NSMutableArray实例的指针(假设您的属性具有keep属性),因此对其中一个iVar所做的更改也将应用于另一个(因为它们指向同一个对象).
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).
要修复使用不同的NSMutableArray初始化数组的情况,
To fix that initialize your arrays with different NSMutableArray's:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
self.modelArray = [NSMutableArray array];
self.detailArray = [NSMutableArray array];
...
这篇关于Objective-C appDelegate数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!