I'm trying to do a pickerView but I'm getting bad acess:
here is my code
-(void) viewWillAppear:(BOOL)animated {
list = [[NSArray alloc]init];
[self populateList]
}
-(void) populateList {
NSString *path = [[NSBundle mainBundle] pathForResource:#"nameoffile" ofType:#"txt"];
NSString *file = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
list = [file componentsSeparatedByString:#"\n"];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return (NSString *)[list objectAtIndex:row]; //here I'm getting bad acces
}
The error is: "Thread 1: EXC_BAD_ACCESS(code=1, address=0xa001cc65)"
NSArray returned by componentsSeparatedByString: is autoreleased value so you need to retain it.
You should remove:
list = [[NSArray alloc]init];
and add retain to:
list = [[file componentsSeparatedByString:#"\n"] retain];
Related
I must be doing something wrong here. My SQLite database is working. However, I cannot seem to populate the tname into a picker view while the picked populates three text fields tname, latitude, and longitude.
Info: Two picker views that are independent from each other, they both read the same sqlite db.
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *array1;
sqlite3 *towerDB;
NSString *dbPathString;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//UIPickerView *pickerview1;
//array1 = [[NSMutableArray alloc]init];
[[self pickerview1]setDelegate:self];
[[self pickerview1]setDataSource:self];
[self displayTower];
}
- (void)displayTower
{
array1 = [[NSMutableArray alloc] init];
sqlite3_stmt *statement;
if (sqlite3_open([dbPathString UTF8String], &towerDB)==SQLITE_OK) {
[array1 removeAllObjects];
NSString *querySql = [NSString stringWithFormat:#"SELECT * FROM TOWERS"];
const char* query_sql = [querySql UTF8String];
// sqlite3_clear_bindings(statement);
// sqlite3_reset(statement);
if (sqlite3_prepare(towerDB, query_sql, -1, &statement, NULL)==SQLITE_OK) // NOT OK
//This Code works in a TableView!!
//Will NOT work in a PickerView
{
while (sqlite3_step(statement)==SQLITE_ROW)
{
NSString *tname = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 1)];
NSString *latitude = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 2)];
NSString *longitude = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 3)];
// NSString *ds2 = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 4)];
NSString *PickerTower = [[NSString alloc] initWithFormat:#"%#", tname];
NSString *lat1 = [[NSString alloc] initWithFormat:#"%#", latitude];
NSString *long1 = [[NSString alloc] initWithFormat:#"%#", longitude];
NSArray *array = [[NSArray alloc] initWithObjects:PickerTower, nil];
[array1 addObject:array];
NSLog(#"Lat/Long %# / %#", lat1, long1);
}
}
}
}
#pragma mark Picker Data Source Methods
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
//ONE Colume
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
//data view how many items?
return [array1 count];
// return [_array2 count];
}
#pragma mark Picker Delegate Methods
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [array1 objectAtIndex:row];
//return [self->array1 objectAtIndex:row];
// array1 = [[NSMutableArray alloc] init];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
long select = row;
NSLog(#"PickerView %ld", select);
}
#end
You have to changed this code in the method name displayTower and code lines -
[array1 addObject:array];
NSLog(#"Lat/Long %# / %#", lat1, long1);
with -
[array1 addObject:array];
NSLog(#"Lat/Long %# / %#", lat1, long1);
[[self pickerview1] reloadAllComponents];
may be it will help you, or feel free.
I'm trying to do a list of lists... but when I use [listaCidades count] ...i'm getting throwing exception (sorry for long question but I mean that all this method is relevant for the question)
-(void) preencherCidades {
for (int iCnt = 0; iCnt < [listaEstados count]; iCnt++) {
NSString *estado = [listaEstados objectAtIndex:iCnt];
NSArray *listaNomeCidades = nil;
NSMutableArray *_listaCidades = [[NSMutableArray alloc]init];
NSString *path = [[NSBundle mainBundle] pathForResource:estado ofType:#"txt"];
NSString *file = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
listaNomeCidades = [[file componentsSeparatedByString:#"\n"]retain];
for (int iCnt2 = 0; iCnt2 < [listaNomeCidades count]; iCnt2++) {
NSArray *listaNomesPrefeitos = nil;
NSArray *listaPartidosPrefeitos = nil;
NSArray *listaVereadores = nil;
NSString *pathNomePrefeitos = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"prefeito-nome-%#",[listaNomeCidades objectAtIndex:iCnt2]] ofType:#"txt"];
NSString *fileNomePrefeitos = [NSString stringWithContentsOfFile:pathNomePrefeitos encoding:NSUTF8StringEncoding error:NULL];
listaNomesPrefeitos = [[fileNomePrefeitos componentsSeparatedByString:#"\n"]retain];
NSString *pathPartidoPrefeitos = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"prefeito-partido-%#",[listaNomeCidades objectAtIndex:iCnt2]] ofType:#"txt"];
NSString *filePartidoPrefeitos = [NSString stringWithContentsOfFile:pathPartidoPrefeitos encoding:NSUTF8StringEncoding error:NULL];
listaPartidosPrefeitos = [[filePartidoPrefeitos componentsSeparatedByString:#"\n"]retain];
NSString *pathVereadores = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"vereadores-%#",[listaNomeCidades objectAtIndex:iCnt2]] ofType:#"txt"];
NSString *fileVereadores = [NSString stringWithContentsOfFile:pathVereadores encoding:NSUTF8StringEncoding error:NULL];
listaVereadores = [[fileVereadores componentsSeparatedByString:#"\n"]retain];
Prefeito *prefeito = nil;
if([listaNomesPrefeitos count] > 0 && [listaPartidosPrefeitos count]>0)
prefeito = [[Prefeito alloc]initWithNome:[listaNomesPrefeitos objectAtIndex:0] partido:[listaPartidosPrefeitos objectAtIndex:0] id:iCnt2];
Cidade *cidade = [[Cidade alloc]initWithNome:[listaNomeCidades objectAtIndex:iCnt2] prefeito:prefeito listaVereadores:listaVereadores id:iCnt2];
[_listaCidades addObject:cidade];
}
[listaCidades addObject:_listaCidades];
}
}
By looking at your answer [Cidade isEqualToString:]:unrecognized selector to instance 0x1cec00. I came to know that that is the only point where string is expected but you are returning Object.
Its good that you solve the issue. Happy Coding.
I solved this with
NSMutableArray *listaCidades2 = (NSMutableArray *)[listaCidades objectAtIndex:indiceEstado];
Cidade *cidade = (Cidade *)[listaCidades2 objectAtIndex:row];
return cidade.nome;
instead of:
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
NSMutableArray *listaCidades2 = (NSMutableArray *)[listaCidades objectAtIndex:indiceEstado];
return [listaCidades2 objectAtIndex:row];
}
Can somebody tell me what I am doing wrong here. I am trying to initialize a string from a list of predefined names, but for some reason it doesn't work for NSString that is a class field:
MyController.h:
#interface MyController:UIViewController
{
NSString *text;
}
MyController.m:
-(void) viewDidLoad
{
[super viewDidLoad];
NSArray *list = [NSArray arrayWithObjects:#"A", #"B", #"C", nil];
NSString* temp= [list objectAtIndex:0]; // temp = "A"
text = [list objectAtIndex:0]; // Why text = nil ????
text = #"Hello"; // does not work either
}
Turns out the debugger is wrong in this case.
Try setting text equal to NSString *text = [NSString stringWithFormat:#"%#", [list objectAtIndex:0]];
I'm parsing something right now and i want to display it in a cell i', using this code for my tableview but i also want it without Tablview
NSString *const JsonDataUrl = [NSString stringWithFormat: #"%#", appdownloadurl];
NSString *jsonString = [NSString
stringWithContentsOfURL:[NSURL URLWithString:JsonDataUrl]
encoding:NSUTF8StringEncoding
error:nil];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
parser = nil;
[self setTableData:[results objectForKey:#"resultCount"]];
This works great but when i place this line in viewdidload
NSDictionary *item = [tableData objectAtIndex:[indexPath row]];
NSLog(#"Apple: %#", [item objectForKey:#"price"]);
And error shows up on this line;
NSDictionary *item = [tableData objectAtIndex:[indexPath row]];
//Unknown recieiver 'indexPath'l did you mean NSIndexPath?
does anyone know how to fix this?
Do you declare any variable called indexPath in your viewDidLoad method? You can't just use the indexPath from your table view methods in viewDidLoad arbitrarily.
NSDictionary *item = [tableData objectAtIndex:[indexPath row]]; suggests you are trying to load from an NSArray, you probably want to try something like:
NSDictionary *item = [tableData objectForKey:#"Some Key"];
I made some test with the UISearchDisplayController and I found some strange behavior I can not explain properly.
Please take a look at the following code:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return numOfRecords;
}
- (NSArray*) search:(NSString*)query {
// Prepare URL request to download statuses from Twitter
NSString *urlString = [NSString stringWithFormat:#"http://someaddress/search.ac?term=%#", query];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSArray *parsedResult = [json_string JSONValue];
return parsedResult;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *kCellID = #"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
int i = [indexPath row];
if ( i >= [searchResult count] ) return cell;
NSString *res = [searchResult objectAtIndex:i];
[[cell textLabel] setText:res];
return cell;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
// WEB Request
NSArray *entries = [self search:searchString];
numOfRecords = [entries count];
NSMutableArray *entryTitles = [[NSMutableArray alloc] init];
for (int i=0; i<numOfRecords; i++) {
NSDictionary *entry = [entries objectAtIndex:i];
[entryTitles addObject:[entry objectForKey:#"title"]];
}
searchResult = entryTitles;
return YES;
}
The searchResult variable is a member variable of type NSArray. This code works fine, however if I change the assignment of searchResult to
searchResult = [NSArray arrayWithArray: entryTitles];
The program crashes after typing the second letter in the search field with a EXC_BAD_ACCESS.
Can somebody explain what is the problem that causes this error?
You probably just need to retain it:
searchResult = [[NSArray arrayWithArray: entryTitles] retain];
You need to do this because arrayWithArray just creates an autoreleased object that will be released in the near future. You need to add your retain to take ownership.
Once you've taken ownership, don't forget to release it somewhere.
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
// WEB Request
NSArray *entries = [self search:searchString];
[searchResult autorelease];
searchResult = [[entries valueForKeyPath:"#unionOfObjects.title"] retain];
return YES;
}
I ran across the same issue. My problem was that in cellForRowAtIndexPath I was releasing the object in the search results array after loading the string value into the cell for display.
Consequently, when I tried to search for anything it immediately crashed.
Check to make sure you aren't releasing the objects that you are searching against.