duplicates data while adding into table
In my app when i insert data by clicking on add button data will be inserted into database and table.record will be inserted perfectly but when i add that data into table it duplicates the database data..here is the code:
NSString *insertData=[NSString stringWithFormat:@"insert into tbl_Bills(Amount,Note,Due_On) values ('%f','%@','%@')",addAmountInDouble,val,due];
[database executeQuery:insertData];
NSLog(@"inert query: %@",insertData);
NSLog(@"value inserted");
NSString *countQuery = [NSString stringWithFormat:@"Select Bill_Id,Entry_Date,Amount,Note,Due_On from tbl_Bills"];
NSArray *countArray1 = [database executeQuery:countQuery];
NSLog(@"Query:%@",countArray1);
[BillTableArray addObjectsFromArray:countArray1];
NSLog(@"Count array开发者_运维知识库 %@",countQuery);
NSLog(@"table array:%@",BillTableArray);
[database close];
[table reloadData];
count array is fine but table array duplicates the value..i also initialize table array in viewDidLoad()
method.
first of all you need to clear your table array before adding new objects :
[BillTableArray removeAllObjects];
after add new updated objects :
[BillTableArray addObjectsFromArray:countArray1];
This is because you are not clearing data out of BillTableArray before adding the new data into it. You are rerunning your query across the entire table - thus retrieving all of your records again, including the ones you've already set up in BillTableArray on the initial view load.
The problem is this line:
[BillTableArray addObjectsFromArray:countArray1];
BillTableArray is already loaded with data from your initial viewDidLoad call, but the query you executed retrieves all of this data from the database again, and this line is adding all of those objects to the array for a second time. So you are probably seeing duplicates of everything except the newly added items.
You probably just need to do:
BillTableArray = [countArray1 retain];
or something similar (don't forget to retain/release objects appropriately to ensure you don't lose them or leak them, not sure how BillTableArray is declared.
BillTableArray
presumably contains all the data you already had in the table. When you re-query the database to get your added value, you will be returning everything, then adding it all again.
So, either
- Specifically add only the new objects to
BillTableArray
- Change your countQuery to only return the new object
- Replace all the contents of
BillTableArray
withcountArray1
[BillTableArray addObjectsFromArray:countArray1];
adds all the objects from array countArray1. So I guess the existing objects in BillTableArray
are not removed before adding the new objects. This creates duplicates. To remove duplicates, just remove all the objects of BillTableArray
and then add the objects from countArray1
.
Just a small note, please make sure you name the variables starting with a lower case alphabet.
精彩评论