Iphone xcode simulator crashes when I move up and down on a table row - iphone

I can't get my head round this. When the page loads, everything works fine - I can drill up and down, however 'stream' (in the position I have highlighted below) becomes not equal to anything when I pull up and down on the tableview. But the error is only sometimes. Normally it returns key/pairs.
If know one can understand above how to you test for // (int)[$VAR count]} key/value pairs
in a NSMutableDictionary object
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *FirstLevelCell = #"FirstLevelCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:FirstLevelCell];
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:FirstLevelCell] autorelease];
}
NSInteger row = [indexPath row];
//NSDictionary *stream = (NSDictionary *) [dataList objectAtIndex:row];
NSString *level = self.atLevel;
if([level isEqualToString:#"level2"])
{
NSMutableDictionary *stream = [[NSMutableArray alloc] init];
stream = (NSMutableDictionary *) [dataList objectAtIndex:row];
// stream value is (int)[$VAR count]} key/value pairs
if ([stream valueForKey:#"title"] )
{
cell.textLabel.text = [stream valueForKey:#"title"];
cell.textLabel.numberOfLines = 2;
cell.textLabel.font =[UIFont systemFontOfSize:10];
NSString *detailText = [stream valueForKey:#"created"];
cell.detailTextLabel.numberOfLines = 2;
cell.detailTextLabel.font= [UIFont systemFontOfSize:9];
cell.detailTextLabel.text = detailText;
NSString *str = #"http://www.mywebsite.co.uk/images/stories/Cimex.jpg";
NSData *imageURL = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:str]];
UIImage *newsImage = [[UIImage alloc] initWithData:imageURL];
cell.imageView.image = newsImage;
[stream release];
}
}
else
{
cell.textLabel.text = [dataList objectAtIndex:row];
}
return cell;
}
Thanks for your time

You are both leaking and over-releasing the stream dictionary:
NSMutableDictionary *stream = [[NSMutableArray alloc] init]; // <-- Create a new dictionary
stream = (NSMutableDictionary *) [dataList objectAtIndex:row]; // <-- Overwrite the reference with another dictionary. Previous dictionary is lost...
...
[stream release]; // <-- You are releasing an object you don't have the ownership.
You should remove the dictionary creation as it is useless and the release as you don't own the object.

I didn't really understand the question, but...
You can test for number of values in a dictionary by:
if ([[myDictionary allKeys] count] == someNumber) {
// do something...
}

Related

getting data in connectionDidFinishLoading,but ubable to use those data in cellForRowAtIndexPath method

I am developing an iphone application. In this i have to generate user profile form dynamically according to field information coming from the server.
So, if there are 5 fields in response i want ton create 5 labels from those data to display in cell of uitableview.
Not that i am getting the name of fields for user profile, not the values of profile.
I want to generate form dynamically from those data.
I'm able to get those data in NSMutableArray but in cellForRowAtIndexPath method its showing null.
How can i solve this?
My code snippet is as follow.
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
if (connection)
{
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//You've got all the data now
//Do something with your response string
// NSLog(#"Response:%#",responseString);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *object = [parser objectWithString:responseString error:nil];
NSString *pec_count = [object valueForKey:#"peculiarity_count"];
NSDictionary *pecs = [object valueForKey:#"peculiarities"];
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:nil];
[array addObject:#""];
for (int j= 1; j <= [pec_count integerValue] ; j++) {
NSString *val = [NSString stringWithFormat:#"%#%d",#"pec_",j];
NSString *pec_i = [pecs valueForKey:val];
NSString *modifiedString = [pec_i stringByReplacingOccurrencesOfString:#"_" withString:#" "];
NSString *capitalisedSentence = [modifiedString stringByReplacingCharactersInRange:NSMakeRange(0,1)
withString:[[modifiedString substringToIndex:1] capitalizedString]];
[array insertObject:capitalisedSentence atIndex:j];
}
self.peculiarity = array;
[self.table reloadData];
}
for (int j=0 ; j < [self.peculiarity count] ; j++) {
NSLog(#"info:%#", [self.peculiarity objectAtIndex: j]);
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UIButton *racebtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
racebtn.frame = CGRectMake(240, 7, 10, 15);
[racebtn setBackgroundImage:[UIImage imageNamed:#"select.png"] forState:UIControlStateNormal];
[racebtn addTarget:self action:#selector(selectRace:)forControlEvents:UIControlEventTouchUpInside];
NSLog(#"cell=%#",[self.peculiarity objectAtIndex:3]);
}
Any help will be appreciated.
Thank you.
in connectionDidFinishLoading: method replace the following line:
self.peculiarity = array; with,
self.peculiarity = [[NSMutableArray alloc] initWithArray:array];
and in cellForRowAtIndexPath method add the following line of code:
cell.textLabel.text = [self.peculiarity objectAtIndex:indexPath.row];
hope this will help you.
Note: If you did not allocated self.peculiarity NSMutableArray then alloc that array like bellow..
if (self.peculiarity == nil)
self.peculiarity = [[NSMutableArray alloc] init];
and then assign that array to this array like bellow..
self.peculiarity = array;
after in cellForRowAtIndexPath: method just set that value or name to the textLabel Of the UITableViewCell like bellow..
cell.textLabel.text = [self.peculiarity objectAtIndex:indexPath.row];
see whole example with that method..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UIButton *racebtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
racebtn.frame = CGRectMake(240, 7, 10, 15);
[racebtn setBackgroundImage:[UIImage imageNamed:#"select.png"] forState:UIControlStateNormal];
[racebtn addTarget:self action:#selector(selectRace:)forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:racebtn];
cell.textLabel.text = [self.peculiarity objectAtIndex:indexPath.row];
}
return cell;
}
I already have checked all above solutions before, Then finally i got solution for this. The problem was that my cell was getting loaded before arrival of data. So i used synchronous request to the server.
Code is below for this :
NSString *path = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"path"];
NSString *address = [NSString stringWithFormat:#"%#%#%#%#", path,#"users/",#"peculiarity/",self.tablename];
NSURL *URL = [NSURL URLWithString:address];
NSLog(#"%#",address);
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[URL host]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLCacheStorageAllowedInMemoryOnly
timeoutInterval:60.0];
[request setHTTPMethod:#"GET"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (data) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"data:%#",responseString);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *object = [parser objectWithString:responseString error:nil];
pecs = [object valueForKey:#"pec_values"];
for (int j =0; j < [pecs count] ; j++) {
NSLog(#"values:%#",[pecs objectAtIndex:j]);
}
self.peculiarity = array;
}
else {
// Handle error by looking at response and/or error values
NSLog(#"%#",error);
}

Reverse array content?

I am populating a table view with information, but would like it to be populated in reverse, so that any newly added cells (new email messages) would appear on the top, not the bottom.
What am I doing wrong?
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"MailCell";
MailCell *cell = (MailCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MailCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
// SLICK
// Anything that should be the same on EACH cell should be here.
UIView *myBackView = [[UIView alloc] initWithFrame:cell.frame];
myBackView.backgroundColor = [UIColor colorWithRed:15.0/255.0 green:140.0/255.0 blue:198.0/255.0 alpha:1];
cell.selectedBackgroundView = myBackView;
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.messageText.textAlignment = NSTextAlignmentLeft;
cell.messageText.lineBreakMode = NSLineBreakByTruncatingTail;
}
NSUInteger row = [indexPath row];
// Extract Data
// Use the message object instead of the multiple arrays.
CTCoreMessage *message = [[self allMessages] objectAtIndex:row];
// Sender
CTCoreAddress *sender = [message sender];
NSString *senderName = [sender name];
// Subject
NSString *subject = [message subject];
if ([subject length] == 0)
{
subject = #"(No Subject)";
}
// Body
BOOL isPlain = YES;
NSString *body = [message bodyPreferringPlainText:&isPlain];
body = [body stringByReplacingOccurrencesOfString:#"\n" withString:#" "];
body = [body stringByReplacingOccurrencesOfString:#"\r" withString:#" "];
// Populate Cell
[[cell nameText] setText:senderName];
[[cell subjectField] setText:subject];
[[cell messageText] setText:body];
if ([message isUnread])
{
UIColor *myColor = [UIColor colorWithRed:15.0/255.0 green:140.0/255.0 blue:198.0/255.0 alpha:1.0];
cell.nameText.textColor = myColor;
}
else
{
cell.nameText.textColor = [UIColor blackColor];
}
return cell;
}
How I am loading the array:
- (NSMutableArray *)allMessages
{
if (_allMessages == nil)
{
_allMessages = [[NSMutableArray alloc] init];
}
return _allMessages;
}
You are pulling from NSArray Index [indexPath row] meaning you are starting at index 0 and going to n. Which means you are not in reverse order. You need to reverse your array first. A simple way would be:
- (void)viewWillAppear:(BOOL)animated
{
NSArray *allMessages = [self allMessages];
NSArray* reversedMessages = [[allMessages reverseObjectEnumerator] allObjects];
}
Then in your cellForRowAtIndexPath method you can do:
CTCoreMessage *message = [reversedMessages objectAtIndex:row];

array returns null value ,arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];

I am having a problem with displaying NSArray values in a UITableView. In my code I am getting nil value.
arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
values = [responseString JSONValue];
array = [[NSMutableArray alloc] init];
NSMutableArray *arrTitle = [[NSMutableArray alloc] init];
NSMutableArray *arrValues = [[NSMutableArray alloc] init];
array =[values valueForKey:#"rates"];
NSLog(#"array values:--> %#",array);
// NSLog(#"values:--> %#",values);
// NSLog(#"Particular values:--> %#",[[values valueForKey:#"rates"] valueForKey:#"AED"]);
tempDict1 = (NSMutableDictionary *)array;
NSArray *arr;// =[[NSArray alloc]init];
arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];
NSLog(#"arr-->%#",arr);
NSString *subStar = #"=";
[arrTitle removeAllObjects];
[arrValues removeAllObjects];
for (int i=0; i<[arr count]-1; i++)
{
[arrTitle addObject:[[arr objectAtIndex:i] substringToIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])-1]];
[arrValues addObject:[[arr objectAtIndex:i] substringFromIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])]];
NSLog(#"arrTitle is:--> %#",arrTitle);
}
tempDict1 = (NSMutableDictionary*)[array objectAtIndex:0];
array = [values valueForKey:#"rates"];
NSLog(#"tempDict--%#",[tempDict1 objectForKey:#"AED"]);
[array retain];
[tbl_withData reloadData];
}
uitableview code is below
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"array-->%#",array);
return [array count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
intIndexPath = indexPath.row;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.font = [UIFont systemFontOfSize:8];
cell.textLabel.numberOfLines = 4;
}
// NSLog(#"data is like:--> %#",array);
// cell.textLabel.text= [NSString stringWithFormat:#"%#",[array objectAtIndex:intIndexPath]];
cell.textLabel.text =[array objectAtIndex:intIndexPath];
return cell;
}
Look through table view programming guide
https://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/AboutTableViewsiPhone/AboutTableViewsiPhone.html
You have to implement UITableView delegate methods in your class to fill table view with content.
Also see this:
https://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/CreateConfigureTableView/CreateConfigureTableView.html#//apple_ref/doc/uid/TP40007451-CH6-SW10
Here is code:
//this is your dictionary:
self.values = [[[NSMutableDictionary alloc] init] autorelease];
//filled it with values:
[self.values setObject:#"201" forKey:#"ams"];
[self.values setObject:#"500.50" forKey:#"hyd"];
[self.values setObject:#"200.10" forKey:#"guj"];
[self.values setObject:#"400" forKey:#"afgd"];
//now get an array of keys out of it. Can do it anywehe... For example in connectionDidFinishLoading method
self.keys = [[[NSArray alloc] initWithArray:[values allKeys]] autorelease];
Now cellForRoAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.font = [UIFont systemFontOfSize:8];
cell.textLabel.numberOfLines = 4;
}
NSString *currentKey = [self.keys objectAtIndex:indexPath.row];
NSString *currentValue = [self.values objectForKey:currentKey];
NSString *cellText = [NSString stringWithFormat:#"%#:%#", currentKey, currentValue];
cell.textLabel.text = cellText;
return cell;
}
It worked on my machine..

UIPickerView in Detailview with .PLIST

I've searched the web + stackoverflow for a solution.
I've an UITableView with information from a .plist file. The plist file have childs. Like the image.
plist http://www.afbeeldingenuploaden.nl/uploads/648899Schermafbeelding%202011-06-12%20om%2009.50.28.png
When i go to DetailView it will display information out of an UIPickerView that's included in the view. I want to display information from the child in the pickerview, the last level. Like the image.
plist1 http://www.afbeeldingenuploaden.nl/uploads/740501Schermafbeelding%202011-06-12%20om%2012.03.40.png
The problem is that i can't reach the last level from the plist in the UIPickerview with my code.
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
NSDictionary *dictionary = [tableDataSource objectAtIndex:row];
return [dictionary objectForKey:#"days"];
}
I use in my tableview for the detailview to reach the last level of the plist.
NSString currentLevel
Can anyone help me out with this, i'm stuck.
As I read the plist, it has an array of dictionaries first of which has a dictionary as one of its values at the second array level. Based on that, your method should be,
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
NSDictionary *dictionary = [tableDataSource objectAtIndex:row];
return [[dictionary objectForKey:#"New item"] objectForKey:#"days"];
}
This will work for the plist in the image. However if more members are added they should adhere to the same structure.
- (void)viewDidLoad {
[super viewDidLoad];
NSString *Path = [[NSBundle mainBundle] bundlePath];
NSString *DataPath = [Path stringByAppendingPathComponent:#"Diyet.plist"];
NSDictionary *tempDict = [[NSDictionary alloc] initWithContentsOfFile:DataPath];
self.data = tempDict;
[tempDict release];
NSArray *tempArray = [[NSArray alloc] init];
self.tableDataSource = tempArray;
[tempArray release];
self.tableDataSource = [data objectForKey:#"Bitki"];
pickerView.delegate = self;
pickerView.dataSource = self;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// Configure the cell.
cell.textLabel.text = [[tableDataSource objectAtIndex:indexPath.row] objectForKey:#"name"];
cell.textLabel.numberOfLines = 2;
cell.textLabel.font = [UIFont boldSystemFontOfSize:16];
tableView.scrollEnabled = NO;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *dictionary = [tableDataSource objectAtIndex:indexPath.row];
NSArray *modelle = [dictionary objectForKey:#"DETAIL"];
if([modelle count] == 0) {
DetailController *dvController = [[DetailController alloc] initWithNibName:#"DetailController" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:dvController animated:YES];
dvController.names.text = [dictionary objectForKey:#"name"];
} else {
BootViewController *rvController = [[BootViewController alloc] initWithNibName:#"BootViewController" bundle:[NSBundle mainBundle]];
rvController.currentLevel += 1;
rvController.currentTitle = [dictionary objectForKey:#"name"];
[self.navigationController pushViewController:rvController animated:YES];
rvController.tableDataSource = modelle;
[rvController release];
}
}

Turning additional strings in this JSON array into a UITableView Detail

I have a NSURL request that brings back an array of "name" and "phone", "etc"... The "name" Key shows up fine on the master table, but I'm having trouble figuring out how to get the rest of the array to show up on the detail table when I select the row. (I have the DetailerTableViewController working to accept the view). Any help would be appreciated.
Thanks,
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [rowsArray count];
NSLog(#"row count: %#",[rowsArray count]);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
NSDictionary *dict = [rowsArray objectAtIndex: indexPath.row];
cell.textLabel.text = [dict objectForKey:#"name"];
cell.detailTextLabel.text = [dict objectForKey:#"loginName"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.0/255.0 green:207.0/255.0 blue:255.0/255.0 alpha:1.0];
self.title = NSLocalizedString(#"Master", #"Master");
NSURL *url = [NSURL URLWithString:#"http://10.0.1.8/~imac/iphone/jsontest.php"];
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url];
NSLog(jsonreturn); // Look at the console and you can see what the results are
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSError *error = nil;
// In "real" code you should surround this with try and catch
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (dict)
{
rowsArray = [dict objectForKey:#"member"];
[rowsArray retain];
}
NSLog(#"Array: %#",rowsArray);
NSLog(#"count is: %i", [self.rowsArray count]);
[jsonreturn release];
}
You need to implement:
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
to handle row selection and to push the view controller for the detail view.