seggy seggy - 2 months ago 22
iOS Question

How to store value in array?

lookupAllForSQL is a database function.
The table name and identifier are dynamic.

for (int i=0; i<FavIdent.count; i++)
{
NSString *strfavarry = [NSString stringWithFormat:@"SELECT Title FROM %@ WHERE identifire='%@'",[FavTablename objectAtIndex:i],[FavIdent objectAtIndex:i]];
FavTitle = [FavData lookupAllForSQL:strfavarry];

}


FavTitle should retain only last row found, but I want all the indicated columns.

Answer

lookupAllForSQL is returning an array, so the value you store in FavTitle (which should be favTitle - variables start with a lower case letter by convention) is being replaced each time, resulting in the last value being left after the loop exits.

You need to use an NSMutableArray and append the sub-array each time through the loop:

NSMutableArray *tempArray = [NSMutableArray new];
for (int i=0; i<FavIdent.count; i++)
{
    NSString *strfavarry = [NSString stringWithFormat:@"SELECT  Title FROM %@ WHERE identifire='%@'",[FavTablename objectAtIndex:i],[FavIdent objectAtIndex:i]];
    [tempArray addObjectsFromArray:[FavData lookupAllForSQL:strfavarry]];
}
favTitle = [tempArray copy];   // Convert it back to an NSArray

You should also use prepared SQL statements rather than string interpolation to guard against SQL injection.

Comments