ok I'm learning to use xCode(5) and I want to use a csv file (screenshot) to read data to store into 7 separate arrays. However, I'm having problems separating the 7 values. I know I'm supposed to use "componentsSeparatedByString" in my case, by ","...but Idk where to place it. Any advice would be appreciated!
csv screenshot: http://i61.tinypic.com/qz5ie8.png
*7th value is " ", used for other purposes.
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
NSError *error;
NSString *allEntries = [NSString stringWithContentsOfFile:#"fighterbase.csv" encoding:NSUTF8StringEncoding error:&error];
NSArray *rows = [allEntries componentsSeparatedByString:#"\n"];
_names = [[NSMutableArray alloc] init];
_origins = [[NSMutableArray alloc] init];
_ages = [[NSMutableArray alloc] init];
_heights = [[NSMutableArray alloc] init];
_weights = [[NSMutableArray alloc] init];
_games = [[NSMutableArray alloc] init];
_images = [[NSMutableArray alloc] init];
for(int i = 0; i < [rows count]; i++)
{
[_names addObject:[rows objectAtIndex:0]];
[_origins addObject:[rows objectAtIndex:1]];
[_ages addObject:[rows objectAtIndex:2]];
[_heights addObject:[rows objectAtIndex:3]];
[_weights addObject:[rows objectAtIndex:4]];
[_games addObject:[rows objectAtIndex:5]];
[_images addObject:[rows objectAtIndex:6]];
}
NSLog(#"Name: %# Origin: %# Age:%#", [_names objectAtIndex:0], [_origins objectAtIndex:0], [_ages objectAtIndex:0]);
}
This should do the trick:
for(int i = 0; i < [rows count]; i++)
{
NSArray *arrayLine = [[row objectAtIndex:i] componentsSeparatedByString#","];
[_names addObject:[arrayLine objectAtIndex:0]];
[_origins addObject:[arrayLine objectAtIndex:1]];
[_ages addObject:[arrayLine objectAtIndex:2]];
[_heights addObject:[arrayLine objectAtIndex:3]];
[_weights addObject:[arrayLine objectAtIndex:4]];
[_games addObject:[arrayLine objectAtIndex:5]];
[_images addObject:[arrayLine objectAtIndex:6]];
}
But in your image, I didn't see there was a 7th value, which may be crash it if it doesn't exist. Well, you said "*7th value is " "", so you may want to manage it.
Related
Below is my Code, When I Add Dictionary into NSMutableArray that time it works well but when I Put NSLog It will throw an Exception. So, Please Help me
//-->
arrMain = [[NSMutableArray alloc] init];
NSMutableArray *arrMainMenu = [[NSMutableArray alloc] init];
NSMutableArray *arrMainMenu2 = [[NSMutableArray alloc] init];
for(int i = 0; i < arrParent.count; i++)
{
NSMutableDictionary *dictMain = [arrParent objectAtIndex:i];
if([[dictMain valueForKey:E_UNDER] isEqualToString:#""])
{
NSString *titleMain = [dictMain valueForKey:E_PARAMETER_VALUE_NAME];
NSMutableArray *arrSubMenu = [[NSMutableArray alloc] init];
for (int j = 0; j <arrSub.count; j++)
{
NSMutableDictionary *dictSub = [[arrSub objectAtIndex:j] mutableCopy];
if([titleMain isEqualToString:[dictSub valueForKey:E_UNDER]])
[arrSubMenu addObject:dictSub];
}
if([arrSubMenu count])
{
[dictMain setValue:#"1" forKey:IS_EXAPANDABLE];
[dictMain setValue:#"0" forKey:IS_EXPANDED];
[arrSubMenu insertObject:dictMain atIndex:0]; //Here Add Key-Value Dictionary in Array
[dictMain setValue:arrSubMenu forKey:LIST_ID];
arrSubMenu = [[NSMutableArray alloc] init];
}
else
[dictMain setValue:#"0" forKey:IS_EXAPANDABLE];
[arrMainMenu addObject:dictMain];
}
}
NSLog(#"%#", arrMainMenu); //Here Throw Bad Access exception
[obj_DataModel setFilterMenu:arrMainMenu];
//-->
I am creating a table with multiple columns. In the left column I want to get the indicator name which is stored in a database and I have to check that the indicator id in database and in json (API) matches and then display the name in that column. I have tried some code
In view load method I take values from database and store it in an array
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
indicatorName = [[NSMutableArray alloc] init];
NSString *path = appDelegate.databasePath;
FMDatabase *db = [[FMDatabase alloc] initWithPath:path];
[db open];
NSString *sql = [NSString stringWithFormat:#"SELECT * FROM Topic AS t INNER JOIN TopicIndicators AS ti ON t.Id = ti.TopicId INNER JOIN Indicators AS i ON ti.IndicatorID = i.Id"];// WHERE t.Id = %ld", (long)self.Tid];
FMResultSet *fresult = [db executeQuery:sql];
while ([fresult next])
{
TopicModel *topicModel = [[TopicModel alloc]init];
topicModel.TId = [fresult intForColumn:#"Id"];
topicModel.TTopicType = [fresult stringForColumn:#"TopicType"];
topicModel.TCode = [fresult stringForColumn:#"Code"];
topicModel.TName = [fresult stringForColumn:#"Name"];
topicModel.IId = [fresult intForColumn:#"Id"];
topicModel.ICodeId = [fresult stringForColumn:#"CodeId"];
topicModel.IName = [fresult stringForColumn:#"Name"];
topicModel.INotes = [fresult stringForColumn:#"Notes"];
topicModel.TIId = [fresult intForColumn:#"Id"];
topicModel.TITopicId = [fresult intForColumn:#"TopicId"];
topicModel.TIIndicatorID = [fresult intForColumn:#"IndicatorId"];
[indicatorName addObject:topicModel];
}
[db close];
mainTableData = [[NSMutableArray alloc] init];
[self callPages];
self.title = NSLocalizedString(#"Compare By", nil);
XCMultiTableView *tableView = [[XCMultiTableView alloc] initWithFrame:CGRectInset(self.view.bounds, 5.0f, 5.0f)];
tableView.leftHeaderEnable = YES;
tableView.datasource = self;
[self.view addSubview:tableView];
}
In request finished method I am taking values from json and assigning the values in appropriate columns.
-(void) requestFinished: (ASIHTTPRequest *) request
{
NSString *theJSON = [request responseString];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableArray *jsonDictionary = [parser objectWithString:theJSON error:nil];
headData = [[NSMutableArray alloc] init];
NSMutableArray *head = [[NSMutableArray alloc] init];
leftTableData = [[NSMutableArray alloc] init];
NSMutableArray *left = [[NSMutableArray alloc] init];
rightTableData = [[NSMutableArray alloc]init];
for (NSMutableArray *dictionary in jsonDictionary)
{
Model *model = [[Model alloc]init];
model.cid = [[dictionary valueForKey:#"cid"]intValue];
model.iid = [[dictionary valueForKey:#"iid"]intValue];
model.yr = [[dictionary valueForKey:#"yr"]intValue];
model.val = [dictionary valueForKey:#"val"];
[head addObject:[NSString stringWithFormat:#"%ld", model.yr]];
[left addObject:[NSString stringWithFormat:#"%ld", model.iid]];
[mainTableData addObject:model];
}
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:head];
headData = [[orderedSet array] mutableCopy];
NSOrderedSet *orderedSet1 = [NSOrderedSet orderedSetWithArray:left];
NSMutableArray *arrLeft = [[orderedSet1 array] mutableCopy];
//remove duplicate enteries from header array
[leftTableData addObject:arrLeft];
NSMutableArray *right = [[NSMutableArray alloc]init];
for (int i = 0; i < arrLeft.count; i++)
{
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int j = 0; j < headData.count; j++)
{
/* NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.iid == %ld", [[arrLeft objectAtIndex:i] intValue]];
NSArray *filteredArray = [mainTableData filteredArrayUsingPredicate:predicate];*/
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.iid == %ld AND SELF.yr == %ld", [[arrLeft objectAtIndex:i] intValue], [[headData objectAtIndex:j] intValue]];
NSArray *filteredArray = [mainTableData filteredArrayUsingPredicate:predicate];
NSMutableArray *newArray = [[NSMutableArray alloc] init];
TopicModel *topicModel = [[TopicModel alloc]init];
for (int k = 0; k < arrLeft.count; k++)
{
if (topicModel.IId == arrLeft[k])
{
[newArray addObject:[NSString stringWithFormat:#"%#",topicModel.IName]];
}
}
if([filteredArray count]>0)
{
Model *model = [filteredArray objectAtIndex:0];
[array addObject:model.val];
}
}
[right addObject:array];
}
[rightTableData addObject:right];
}
I am using FMDB, ASIHTTPRequest, SBJSON, XCMultisortTableView.
Please do help.
Well you are creating new TopicModel object which is empty! You need to use the one which you set in your viewDidLoad: method.
for (int k = 0; k < arrLeft.count; k++) {
if ([(TopicModel *)indicatorName[k] IId] == [arrLeft[k] integerValue]) {
[newArray addObject:[NSString stringWithFormat:#"%#",[(TopicModel *)indicatorName[k] IName]];
}
}
I have a function which prepares data for my UITableView:
- (void) SearchFromMyPosition {
TitleLabelSort = [[NSMutableArray alloc] init];
DistanceLabelSort = [[NSMutableArray alloc] init];
TagValueSort = [[NSMutableArray alloc] init];
DistanceUnitSort = [[NSMutableArray alloc] init];
LatArraySort = [[NSMutableArray alloc] init];
LngArraySort = [[NSMutableArray alloc] init];
// loading
[activityIndicatorObject startAnimating];
NSNumber *latNr1 = [[NSUserDefaults standardUserDefaults] valueForKey:#"api_lat"];
NSNumber *lngNr1 = [[NSUserDefaults standardUserDefaults] valueForKey:#"api_lng"];
double lat1 = [latNr1 doubleValue];
double lng1 = [lngNr1 doubleValue];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSArray *array = [APIConnection GetDataFromUrlAuth];
dispatch_async(dispatch_get_main_queue(), ^{
for (NSString *item in array) {
NSArray *coords = [[[array valueForKey:item] valueForKey:#"location"] componentsSeparatedByString:#"|"];
double lat2 = [[coords objectAtIndex:0] doubleValue];
double lng2 = [[coords objectAtIndex:1] doubleValue];
CLLocation *oldLocation = [[CLLocation alloc] initWithLatitude:lat1 longitude:lng1];
CLLocation *newLocation = [[CLLocation alloc] initWithLatitude:lat2 longitude:lng2];
CLLocationDistance meters = [newLocation distanceFromLocation:oldLocation];
[LatArraySort addObject:[NSString stringWithFormat:#"%f",lat2]];
[LngArraySort addObject:[NSString stringWithFormat:#"%f",lng2]];
[TitleLabelSort addObject:[[array valueForKey:item] valueForKey:#"name"]];
[DistanceLabelSort addObject:[NSString stringWithFormat:#"%f",meters]];
[TagValueSort addObject:item];
[self.myTableView reloadData];
[activityIndicatorObject stopAnimating];
}
});
});
}
This works but I need to sort results by DistanceLabelSort
For sorting CoreData results I use below function and works fine:
- (void) SetTableData {
TitleLabel = [[NSMutableArray alloc] init];
DistanceLabel = [[NSMutableArray alloc] init];
TagValue = [[NSMutableArray alloc] init];
DistanceUnit = [[NSMutableArray alloc] init];
LatArray = [[NSMutableArray alloc] init];
LngArray = [[NSMutableArray alloc] init];
// sorting
NSArray *sortedArray = [DistanceLabelSort sortedArrayUsingComparator:^(NSString *str1, NSString *str2) {
return [str1 compare:str2 options:NSNumericSearch];
}];
NSString *sortIdentStr = [[NSString alloc] init];
unsigned long sortIdent;
NSMutableArray *arrayUnit = [[NSMutableArray alloc] init];
for (int i = 0; i < sortedArray.count; i++) {
sortIdentStr = [sortedArray objectAtIndex:i];
sortIdent = [DistanceLabel indexOfObject:sortIdentStr];
arrayUnit = [self unitStr:sortIdentStr];
[TitleLabel addObject:[TitleLabelSort objectAtIndex:sortIdent]];
[TagValue addObject:[TagValueSort objectAtIndex:sortIdent]];
[LatArray addObject:[LatArraySort objectAtIndex:sortIdent]];
[LngArray addObject:[LngArraySort objectAtIndex:sortIdent]];
[DistanceLabel addObject:[arrayUnit objectAtIndex:0]];
[DistanceUnit addObject:[arrayUnit objectAtIndex:1]];
[self.myTableView reloadData];
[activityIndicatorObject stopAnimating];
}
}
But if I try use this for sorting data from external api function SetTableData is done before I get results from external api.
Finally I found solution and maybe this will be helpful for others:
I added function which checks if the task is done:
- (void)SearchFromMyPositionWithSuccess:(void (^)(void))successHandler failure:(void (^)(void))failureHandler {
TitleLabelSort = [[NSMutableArray alloc] init];
DistanceLabelSort = [[NSMutableArray alloc] init];
TagValueSort = [[NSMutableArray alloc] init];
DistanceUnitSort = [[NSMutableArray alloc] init];
LatArraySort = [[NSMutableArray alloc] init];
LngArraySort = [[NSMutableArray alloc] init];
// loading
[activityIndicatorObject startAnimating];
NSNumber *latNr1 = [[NSUserDefaults standardUserDefaults] valueForKey:#"api_lat"];
NSNumber *lngNr1 = [[NSUserDefaults standardUserDefaults] valueForKey:#"api_lng"];
double lat1 = [latNr1 doubleValue];
double lng1 = [lngNr1 doubleValue];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSArray *array = [APIConnection GetDataFromUrlAuth];
dispatch_async(dispatch_get_main_queue(), ^{
int i = 0;
for (NSString *item in array) {
i++;
NSArray *coords = [[[array valueForKey:item] valueForKey:#"location"] componentsSeparatedByString:#"|"];
double lat2 = [[coords objectAtIndex:0] doubleValue];
double lng2 = [[coords objectAtIndex:1] doubleValue];
CLLocation *oldLocation = [[CLLocation alloc] initWithLatitude:lat1 longitude:lng1];
CLLocation *newLocation = [[CLLocation alloc] initWithLatitude:lat2 longitude:lng2];
CLLocationDistance meters = [newLocation distanceFromLocation:oldLocation];
[LatArraySort addObject:[NSString stringWithFormat:#"%f",lat2]];
[LngArraySort addObject:[NSString stringWithFormat:#"%f",lng2]];
[TitleLabelSort addObject:[[array valueForKey:item] valueForKey:#"name"]];
[DistanceLabelSort addObject:[NSString stringWithFormat:#"%f",meters]];
[TagValueSort addObject:item];
if (i == array.count) {
successHandler();
}
[activityIndicatorObject stopAnimating];
}
});
});
}
And wait for success in this function:
-(void) SearchFromMyPosition {
[self SearchFromMyPositionWithSuccess: ^{
[self SetTableData];
NSLog(#"success");
} failure:^{
NSLog(#"failure");
}];
}
This solves my case :)
I'm having a difficulty with this one I have a method that returns a value of Array of NSDictionary once I pass the return value of an array first it works. I already get the object in my NSLog but when I try to access the objects of my Array of NSDictionary in another method I get the error and I think that I loses the objects of the array.
Here's the method that return an Array of NSDictionary:
-(NSMutableArray *)selectItemDataTbl {
NSMutableArray *l_array_data = [[NSMutableArray alloc] init];
NSString *query = #"SELECT pid, fname, gen_name, type, fu, fprice FROM tbl_selectItem_data";
sqlite3_stmt *l_statement;
if (sqlite3_open([l_SqliteDb UTF8String], &(_database)) == SQLITE_OK) {
if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &l_statement, nil) == SQLITE_OK) {
while(sqlite3_step(l_statement) == SQLITE_ROW){
NSMutableDictionary *l_dataDictionary = [[NSMutableDictionary alloc]init];
NSString *l_pid = [NSString stringWithUTF8String:(char *)sqlite3_column_text(l_statement, 0)];
NSString *l_name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(l_statement, 1)];
NSString *l_genName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(l_statement, 2)];
NSString *l_Type = [NSString stringWithUTF8String:(char *)sqlite3_column_text(l_statement, 3)];
NSString *l_u = [NSString stringWithUTF8String:(char *)sqlite3_column_text(l_statement, 4)];
NSString *l_Price = [NSString stringWithUTF8String:(char *)sqlite3_column_text(l_statement, 5)];
[l_dataDictionary setObject:l_pid forKey:#"pid"];
[l_dataDictionary setObject:l_name forKey:#"name"];
[l_dataDictionary setObject:l_genName forKey:#"genName"];
[l_dataDictionary setObject:l_Type forKey:#"Type"];
[l_dataDictionary setObject:l_u forKey:#"u"];
[l_dataDictionary setObject:l_Price forKey:#"Price"];
[l_array_data addObject:l_dataDictionary];
}
NSLog(#"l_array_data count: %i", [l_array_data count]);
sqlite3_finalize(l_statement);
sqlite3_close(_database);
}
}
return l_array_data;
}
And here my method how I access it I'm calling it on my viewDidLoad:
- (void)selectItemData {
_l_alldataInSelectItem = [[NSMutableArray alloc] init];
_l_prodId = [[NSMutableArray alloc] init];
_l_prodName = [[NSMutableArray alloc] init];
_l_prodGenName = [[NSMutableArray alloc] init];
_l_prodCompType = [[NSMutableArray alloc] init];
_l_prodUom = [[NSMutableArray alloc] init];
_l_prodListPrice = [[NSMutableArray alloc] init];
_l_alldataInSelectItem = [dbc selectItemDataTbl];
_l_selectItemData_Dictionary = [[NSDictionary alloc] init];
for (_l_selectItemData_Dictionary in _l_alldataInSelectItem) {
NSString *Id = [_l_selectItemData_Dictionary valueForKey:#"pid"] ;
NSString *Name = [_l_selectItemData_Dictionary valueForKey:#"name"];
NSString *GenName = [_l_selectItemData_Dictionary valueForKey:#"genName"];
NSString *Type = [_l_selectItemData_Dictionary valueForKey:#"Type"];
NSString *U = [_l_selectItemData_Dictionary valueForKey:#"u"];
NSString *Price = [_l_selectItemData_Dictionary valueForKey:#"Price"];
[_l_prodId addObject:Id];
[_l_prodName addObject:Name];
[_l_prodGenName addObject:GenName];
[_l_prodCompType addObject:GenName];
[_l_prodUom addObject:U];
[_l_prodListPrice addObject:Price];
}
NSLog(#"adsfasdf %#", _l_prodId);
NSLog(#"adsfasdf %i", [_l_alldataInSelectItem count]);
}
But in this method I can't get the value of my array _l_alldataInSelectItem
- (void)textFieldshouldChange {
NSString *searchKey = self.txt_SearchField.text;
NSMutableArray *searchingData = [[NSMutableArray alloc] init];
if (![searchKey isEqualToString:#""]) {
NSLog(#"When TextField text is changed, this will be called");
NSLog(#"textFieldshouldChange _l_alldataInSelectItem: %i", [_l_alldataInSelectItem count]);
}
}
here's how i declare my l_alldataInSelectItem. I declared it on my header file
#property (strong, nonatomic) NSMutableArray *l_alldataInSelectItem, *l_prodId, *l_prodName, *l_prodGenName, *l_prodCompType, *l_prodUom, *l_prodListPrice;
Go systematically through the possibilities.
Possibility 1: There are gremlins somewhere trying to annoy you. We exclude that.
Possibility 2: You never created the data. Set a breakpoint on the return statement in selectItemDataTbl and check it.
Possibility 3: You never stored the array. Well, there is the fact that you store an empty mutable array into _l_alldataInSelectItem which is absolutely pointless, but set a breakpoint on the last statement in selectItemData and check it.
Possibility 4: You stored it and overwrote it. Search for all places where you store to _l_alldataInSelectItem or to a property named l_alldataInSelectItem, set breakpoints everywhere, and check.
Possibility 5 (the stupid one): _l_alldataInSelectItem is a weak instance variable or a weak property.
Possibility 6: You stored it, but looked for it in a different place. Is the self in textFieldshouldChange the same as the self in selectItemData? Set breakpoints and check.
Possibility 7: You are doing something asynchronously. The variable will be set, but much later than you think.
Most important: Put it very strongly in your mind that you did something wrong, and you don't have to solve any magical puzzles, all you need to do is find out what you did wrong.
I have this...
allTableData = [[NSMutableArray alloc] initWithObjects:
[[Food alloc] initWithName:#"1" andDescription:#"Hi man!"],
[[Food alloc] initWithName:#"2" andDescription:#"Hi woman"],
nil ];
How can I do something like that?
NSArray *array = [NSArray arrayWithObjects:#"Hi man",#"Hi woman",nil];
allTableData = [[NSMutableArray alloc] initWithObjects
for(i=0; i<2; i++)
{
NSString *aString = [NSString stringWithFormat:#"%d", i];
[[Food alloc] initWithName:aString andDescription:#"array[i]"];
}
...as well as enter through a cycle?
[[Food alloc] initWithName:aString andDescription:#"array[i]"];
should be
[[Food alloc] initWithName:aString andDescription:array[i]];
In the first case you were adding the string "array[i]", where instead you want to access the i-th element of the array.
Also, there's a shorter way for converting an int to NSString
[NSString stringWithFormat:#"%d", i];
can be replaced by
#(i).stringValue
The # syntax for numbers is a feature introduced by llvm 3.3, that allows you to create NSNumbers literals. NSNumber has then the method stringValue that you can use to get the desired NSString.
Try this
NSArray *array = [NSArray arrayWithObjects:#"Hi man",#"Hi woman",nil];
allTableData = [NSMutableArray array];
for(i=0; i<[array count]; i++){
NSString *aString = [#(i) stringValue];
Food *food = [[Food alloc] initWithName:aString andDescription:array[i]];
[allTableData addObject:food];
}
NSArray *array = [NSArray arrayWithObjects:#"Hi man",#"Hi woman",nil];
NSMutableArray* tableData = [NSMutableArray arrayWithCapacity:array.count];
[array enumerateObjectsUsingBlock:^(id obj,NSUInteger index,BOOL* stop){
[tableData addObject:[[Food alloc] initWithName:[#(index) stringValue] andDescription:obj]];
}];