Connect to peripheral in didSelectRowAtIndexPath - objective-c

I am developing an app using CoreBluetooth. I am able to discover devices from the app and show their names in the table view. I am facing a problem with requirements below:
When used for the first time, the user selects a peripheral from the list. Connection should be established with the peripheral using the Bluetooth Serial Port Profile (SPP). Discovery and connection is simple and accomplished with a single click, minimizing user interaction.
Once a connection has been established between the peripheral device and the app, the app remembers the device and always seeks and connects to it for all subsequent uses.
I have written the following code for this as below for scanning and discovering
- (void)scan
{
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
NSLog(#"options are %#",options);
[self.centralManager scanForPeripheralsWithServices:nil
options:nil];
_txtLogMessage.text = [NSString stringWithFormat:#"%# \n %#",_txtLogMessage.text,#"Scanning started"];
NSLog(#"Scanning started");
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral
*)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
[central connectPeripheral:peripheral options:nil];
self.discoveredPeripheral = peripheral;
_logData = [NSString stringWithFormat:#"Did discover peripheral. peripheral: %# rssi: %#, UUID: %# advertisementData: %# ", peripheral, RSSI, peripheral.UUID, advertisementData];
NSLog(#"%#",_logData);
[_periferalDevices addObject:peripheral.name];
[_tableView reloadData];
}
for connecting the device
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
peripheral.delegate = self;
[self.discoveredPeripheral discoverServices:nil];
NSLog(#"Peripheral Connected");
NSLog(#" started time is %#",_timestring);
//[self.centralManager stopScan];
NSLog(#"Scanning stopped");
[self.data setLength:0];
[peripheral discoverServices:nil];
[peripheral discoverServices:#[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]]];
}
in table view cell for row at index path aim able to get the data to view but aim facing problem in connecting to a peripheral while particular row is selected in the table view
- (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];
}
cell.textLabel.text = [_periferalDevices objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
_discoveredPeripheral.delegate = self;
[self.centralManager connectPeripheral:[_periferalDevices objectAtIndex:indexPath.row]
options:nil];
NSLog(#"discovered peripheral is %#",[_periferalDevices objectAtIndex:indexPath.row]);
NSString *datstr=[_discoveredPeripheral valueForKey:#"identifier"];
NSLog(#"value for key is ........%#",datstr);
}

The errors that you get when you try to use the peripheral object stems from the fact that you added the name of the peripheral to your array rather than the peripheral, itself. Thus, replace
[_periferalDevices addObject:peripheral.name];
With
[_periferalDevices addObject:peripheral];
And, obviously, you'll have to fix wherever you took advantage of just inserting the name. For example, your cellForRowAtIndexPath bears a line that says:
cell.textLabel.text = [_periferalDevices objectAtIndex:indexPath.row];
You'd probably want to replace that with something like:
CBPeripheral *peripheral = _periferalDevices[indexPath.row];
cell.textLabel.text = peripheral.name;
Your didDiscover... is connecting immediately. It probably shouldn't. You should probably only try connecting to the device the user selected. This could cause problems if you try to connect again (I don't know what it does if you try to connect twice). Your didSelectRow... connects on the ones the user chooses, so you should probably leave it at that.
You say "am facing problem connecting". So, what precisely did didFailToConnectPeripheral report?
As an aside, I'm unclear why you're calling discoverServices twice, too. Either discover all services (slow) or discover just the particular service, but you probably don't have to do both.
My original answer (based upon original code sample) is below.
You have code that says:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = cell.textLabel.text;
if([cellText isEqualToString:#""])
{
}
else
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Connected to "
message:cellText delegate:self cancelButtonTitle:#"ok"
otherButtonTitles: nil];
[alert show];
}
_discoveredPeripheral.delegate = self;
[self.centralManager connectPeripheral:_discoveredPeripheral options:nil];
NSLog(#"discovered peripheral is %#", _discoveredPeripheral);
NSString *datstr = [_discoveredPeripheral valueForKey:#"identifier"];
NSLog(#"value for key is ........%#", datstr);
}
You are retrieving the information on the selected cell (though Hot Licks is correct, you should be going to your model, not to the view for that information), retrieving the cellText, but you proceed to use _discoveredPeripheral, which is some variable that bears no obvious relation to the cell the user just selected.
You want to maintain your model of the array of peripherals, and when a user taps on the cell, use the indexPath.row to look up the peripheral in your model array, and use that CBPeripheral in your connection code.

Related

How do to use the tel:// scheme with stringWithFormat

I am trying to create a simple phone book app that allows me to call people from the list. The app lists the names of the contacts and their phone numbers in different sections alphabetically based on the last name. Everything is displaying properly, my issue is when I select a contact and get prompted to "Cancel" or "Call", the "Call" button in the alertView doesn't do anything.
Here is the code I am using (urlString is a global variable):
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog("#didSelectRowAtIndexPath");
NSString *alphabet = [nameIndex objectAtIndex:[indexPath section]];
if([alphabet isEqual:#"A"])
{
UIAlertView *messageAlert = [[UIAlertView alloc] initWithTitle:#"Do you want to call.." message:[SectionA objectAtIndex:indexPath.row] delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Call", nil];
NSString *urlString = [NSString stringWithFormat:#"tel://%#",[SectionA objectAtIndex:indexPath.row]];
[messageAlert show];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
There are more if statements with the same code for the different sections of name/numbers, for the sake of space and time I just added the one section.
Here is where I attempt to make the "Call" button actually call the number:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex != [alertView cancelButtonIndex])
{
NSLog(#"Calling phone number");
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
}
}
The alert displays the proper phone number selected, and when I select "Call" nothing happens. But "Calling phone number" does show up in the output log. Stuck at the moment I'm assuming what I store in urlString isn't correct; or how I'm using urlString isn't correct. Any help would be appreciated, thanks!
Change this line
NSString *urlString = [NSString stringWithFormat:#"tel://%#",[SectionA objectAtIndex:indexPath.row]];
to this
urlString = [NSString stringWithFormat:#"tel://%#",[SectionA objectAtIndex:indexPath.row]];
You shadowed a local variable over a global / instance variable, hence the assigned value never reaches the point you expected. In other words, there are two urlString's existing at that point. A local one and one that is scoped globally / instance wide. Your assignment changed the local one, your attempt to use the value uses the global / instance one.

QuickBlox :How to share image/video in peer to peer chat module?

I am trying to share image/video in chat module. I've referred Sample code for this but couldn't find any help.
Alos I've referred http://quickblox.com/modules/chat/ it says Add live chat functions to your app by plugging in our full featured chat module. Fast, Firewall friendly, Robust & Secure. Does it means I have to purchase full featured chat module ?
Please suggest me the right way.
Thanks
Yes, QuickBlox Chat allows to share files, video/audio between 2 users.
Right now iOS SDK doesn't provide methods for send file, live chat. This feature is under Beta testing right now. We are developing easy interface for end users, and we need more time for this. I hope, we will finish it at the end of December.
However, we allow developers develop this feature themself.
What you need for this?
Just create simple TCP/UDP socket between 2 users and send files, audio/video stream through it
For 1 you need to know each other ip address & port - there is STUN protocol that allow to know own address(IP & port) - here is my iOS implementation of STUN protocol https://github.com/soulfly/STUN-iOS
If you already know your address (IP & port) - just send it to your opponent through simple Chat messages - then do 1 item.
Thats all what you need
UPD:
QuickBlox has released VideoChat and Unlimited API Calls for Developers http://quickblox.com/blog/2013/02/quickblox-updates-videochat-and-unlimited-api-calls-for-developers
So, if you want to play with the code and integrate it with your apps, check the Simple Code Sample for iOS http://quickblox.com/developers/SimpleSample-videochat-ios
You have a uploadMethod like this,
-(IBAction)uploadFile:(id)sender
{
self.imagePicker = [[UIImagePickerController alloc] init];
self.imagePicker.allowsEditing = NO;
self.imagePicker.delegate = self;
self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:self.imagePicker animated:YES completion:nil];
}
and in the QBChatDelegate, you have this method
- (void)completedWithResult:(Result*)result{
// Upload file result
if(result.success && [result isKindOfClass:[QBCFileUploadTaskResult class]])
{
QBCFileUploadTaskResult *res = (QBCFileUploadTaskResult *)result;
NSUInteger uploadedFileID = res.uploadedBlob.ID;
QBChatMessage *message = [[QBChatMessage alloc] init];
message.recipientID = self.opponent.ID;
NSMutableDictionary *msgDict = [[NSMutableDictionary alloc]init];
[msgDict setValue:[NSNumber numberWithInt:uploadedFileID] forKey:#"fileID"];
message.customParameters = msgDict;
[[QBChat instance] sendMessage:message];
}
else
{
NSLog(#"errors=%#", result.errors);
}
}
Here you are getting the uploaded file id, and you are sending this as a message..
In your chatDidReceiveNotification
- (void)chatDidReceiveMessageNotification:(NSNotification *)notification{
QBChatMessage *message = notification.userInfo[kMessage];
if(message.customParameters != nil)
{
NSUInteger fileID = [message.customParameters[#"fileID"] integerValue];
// download file by ID
[QBContent TDownloadFileWithBlobID:fileID delegate:self];
}
}
This method again calls completedWithResult method, add this code there...
if(result.success && [result isKindOfClass:[QBCFileDownloadTaskResult class]]){
QBCFileDownloadTaskResult *res = (QBCFileDownloadTaskResult *)result;
if ([res file]) {
UIImageView* imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:[res file]]];
[self.messages addObject:imageView];
[self.messagesTableView reloadData];
}
}else{
NSLog(#"errors=%#", result.errors);
}
If you want to display the image in your tableView, change your cellForRow like this..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if([[self.messages objectAtIndex:indexPath.row]isKindOfClass:[QBChatMessage class]])
{
static NSString *ChatMessageCellIdentifier = #"ChatMessageCellIdentifier";
ChatMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ChatMessageCellIdentifier];
if(cell == nil){
cell = [[ChatMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ChatMessageCellIdentifier];
}
QBChatMessage *message = (QBChatMessage *)self.messages[indexPath.row];
//
[cell configureCellWithMessage:message is1To1Chat:self.opponent != nil];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
else if ([[self.messages objectAtIndex:indexPath.row]isKindOfClass:[UIImageView class]])
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
if (nil == cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"CellIdentifier"];
}
UIImageView *receivedImage = [self.messages objectAtIndex:indexPath.row];
[cell.contentView addSubview:receivedImage];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
}
I have tried this and this piece of code works.
Cheers.
If your requirement is only for 1-1 chat, then please check this link
http://quickblox.com/developers/SimpleSample-chat_users-ios#Send_files
This will work for 1-1 chat.
But, in case of room I am unable to find any solution as of now. I am trying to figure out. If anybody knows a way, please post here.

UItableviewcontroller cell text label content not displayed

I ve successfully parsed json file in my app but when i tried to display all it in table view its not getting displayed .here is my code.
NSString *urlstr=[NSString stringWithFormat:#"http://minora.p41techdev.net/portal.php"];
NSURL *url=[NSURL URLWithString:urlstr];
NSData *data =[NSData dataWithContentsOfURL:url];
NSError *error;
NSArray *json=(NSMutableArray*) [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
//NSLog(#"%#",json);
NSDictionary *dict =[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"a title", #"more data",nil] forKeys:[NSArray arrayWithObjects:#"titleKey",#"dataKey", nil]];
NSLog(#"1");
NSString *integ = [dict valueForKey:#"id"];
NSString *title=[dict valueForKey:#"title"];
NSString *category=[dict valueForKey:#"category"];
NSString *description=[dict valueForKey:#"description"];
NSString *spectitle=[dict valueForKey:#"spectitle"];
NSString *specvalue=[dict valueForKey:#"specvalue"];
NSArray *arr =[NSArray arrayWithObjects:integ,title,category,description,spectitle,specvalue, nil];
[tablearray addObject:arr];
NSLog(#"%#",tablearray);
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
// Return the number of rows in the section.
return [tablearray count];
NSLog(#"5");
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.textLabel.text=[[tablearray objectAtIndex:indexPath.row] objectAtIndex:1];
return cell;
}
and my json file looks like this
[
{
"id": "1",
"category": "New Category1",
"title": "New Product2",
"description": "Please type a description1",
"imgurl": "http://s.wordpress.org/about/images/wordpress-logo-notext-bg.png",
"spectitle": "Specification",
"specvalue": "Value"
},
{
"id": "2",
"category": "Mobile",
"title": "Samsung",
"description": "Please type a description",
"imgurl": "http://s.wordpress.org/about/images/wordpress-logo-notext-bg.png",
"spectitle": "Price",
"specvalue": "100$"
}
]
Guidance please...
i'm getting thread issue like this
2012-07-20 19:36:03.504 tablevc[2253:f803] 1
2012-07-20 19:36:03.505 tablevc[2253:f803] 2
2012-07-20 19:36:03.507 tablevc[2253:f803] 4
2012-07-20 19:36:03.507 tablevc[2253:f803] 3
2012-07-20 19:36:03.508 tablevc[2253:f803] *** Assertion failure in -[UITableView _createPreparedCellForGlobalRow:withIndexPath:], /SourceCache/UIKit_Sim/UIKit-1914.84/UITableView.m:6061
2012-07-20 19:36:03.508 tablevc[2253:f803] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'
*** First throw call stack:
(0x13d2022 0x1563cd6 0x137aa48 0x9b32cb 0xb6d28 0xb73ce 0xa2cbd 0xb16f1 0x5ad21 0x13d3e42 0x1d8a679 0x1d94579 0x1d194f7 0x1d1b3f6 0x1d1aad0 0x13a699e 0x133d640 0x13094c6 0x1308d84 0x1308c9b 0x12bb7d8 0x12bb88a 0x1c626 0x2ae2 0x2a55 0x1)
terminate called throwing an exception
I don't see the initialization of tablearray anywhere.
Add this to your viewDidLoad method:
tablearray = [[NSMutableArray alloc] init];
I also see that you're inserting an array within an array. This means that when you need to access the correct data (NSString in your case), you must use the correct index:
cell.textLabel.text=[[tablearray objectAtIndex:indexPath.row] objectAtIndex:1];
I used "objectAtIndex:1" because the title string is stored at index 1 in the inner array. A better, more generic approach would be to use NSDictionary. For example:
NSDictionary *dict =[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"a title", #"more data",nil] forKeys:[NSArray arrayWithObjects:#"titleKey",#"dataKey"]];
Also, make sure your delegate returns the correct amount of sections for your table.
Number of sections in tableview is at least one...
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;//It should be at least one.......
}
Write the following code in cellForRowAtIndexPath: method. Otherwise you will get error.
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
I think it will be helpful to you.
call [tableView reloadData] after you add arr in your table array...
[tablearray addObject:arr];
[tableView reloadData]
NSLog(#"2");
hope it helps
You should initialize the cell like this:
- (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];
}
[[cell textLabel] setText:[tablearray objectAtIndex:indexPath.row]];
// Configure the cell...
return cell;
}
You have tablarray with 1 element. This element is an array containing a few entries.
Your data source declares only one cell (tablearray count, which is one).
Your cellForIndexPath method will always look for the first and only the first element in the json array anyway.
Edit: unrelated, but if a field in your json is not set, you'll get nil back, and that'll terminate your array in arrayWithObjects, which will likely cause an out of bounds index down the line.
Be very careful with this method, it's very easy to shoot yourself in the foot with it.

How to store NSMutableArray to NSUserDefaults and show results in TableView?

I want to save the Notifications which come from server in my application and also make a User Interface to give users the ability of chosing which Notification(message) to read. In a scheduled method my client controls for changes inside the server and the communication is in JSON format. I have parsed it and can see the results in NSLog(#"....",..) too. I also control the status of message from the server, if the status equals to 1 i will save the message and add a node to TableView.. Now, can anyone help me about how to transmit datas in NSMutableArray both to NSUserDefaults and TableView? I can Share code or JSON representation too if you want..
It will be better if you could explain with some code.. Thanks
I decided to share some of my code,
as i have writen under the code too, i want to display NSMutableArray in UITableView
`-(IBAction)Accept:(id)sender
{ userName=[[NSString alloc] initWithString:userNameField.text ];
[userNameField setText:userName];
NSUserDefaults *userNameDef= [NSUserDefaults standardUserDefaults];
[userNameDef setObject:userName forKey:#"userNameKey"];
password =[[NSString alloc] initWithString:passwordField.text];
[passwordField setText:password];
NSUserDefaults *passDef=[NSUserDefaults standardUserDefaults];
[passDef setObject:password forKey:#"passwordKey"];
serverIP=[[NSString alloc] initWithString: serverField.text];
[serverField setText:serverIP];
NSUserDefaults *serverDef=[NSUserDefaults standardUserDefaults];
[serverDef setObject:serverIP forKey:#"serverIPKey"];
[userNameDef synchronize];
[serverDef synchronize];
[passDef synchronize];
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"BNTPRO "
message:#"Your User Informations are going to be sent to server. Do you accept?"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:#"Cancel", nil];
[message show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"OK"])
{
if([userNameField.text isEqualToString:#""]|| [passwordField.text isEqualToString:#""] || [serverField.text length]<10)
{
UIAlertView *message1 = [[UIAlertView alloc] initWithTitle:#"BNTPRO "
message:#"Your User Informations are not defined properly!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[message1 show];
[userNameField resignFirstResponder];
[passwordField resignFirstResponder];
return;
}
//## GET code to here**
NSString *str1=[#"?username=" stringByAppendingString:userNameField.text];
NSString *str2=[#"&password=" stringByAppendingString:passwordField.text];
NSString *str3=[str1 stringByAppendingString:str2];
NSString *str4 =[#"http://" stringByAppendingString:serverField.text];
NSURL *url=[NSURL URLWithString:[str4 stringByAppendingString:[#"/ipad/login.php" stringByAppendingString:str3]]];
NSLog(#"%#\n",url);
//get the url to jsondata
NSData *jSonData=[NSData dataWithContentsOfURL:url];
if (jSonData!=nil) {
NSError *error=nil;
id result=[NSJSONSerialization JSONObjectWithData:jSonData options:
NSJSONReadingMutableContainers error:&error];
if (error==nil) {
NSDictionary *mess=[result objectForKey:#"message"];
NSDictionary *messContent=[mess valueForKeyPath:#"message"];
NSDictionary *messDate=[mess valueForKeyPath:#"date"];
NSDictionary *messID=[mess valueForKeyPath:#"ID"];
NSDictionary *messStatus=[mess valueForKey:#"status"];
NSLog(#"%# *** Message %# \n Message Content: %# \n Mesage ID: %# \n Message Date: %#\n \nilhancetin MessageSatus: %#", result, mess, messContent, messID,messDate,messStatus);
NSString*key1=[ result objectForKey:#"key" ];
NSString *s1=[#"http://" stringByAppendingString:serverField.text];
NSString *s2=[s1 stringByAppendingString:#"/ipad/button.php"];
NSURL *url2=[NSURL URLWithString:[s2 stringByAppendingString:[#"?key=" stringByAppendingString:key1]]];
NSLog(#"\n%#\n",url2 );
NSData *data2=[NSData dataWithContentsOfURL:url2];
id result2=[NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
NSMutableArray *mesID = [NSMutableArray array];//saving meesages to NSMutableArray
NSMutableArray *status = [NSMutableArray array];
// i logged here and it saves the data, now i want to display my data in table view
`
save it in NSUserDefaults:
[[NSUserDefaults standardUserDefaults]setObject:yourArray forKey:#"theArray"];
get it from NSUserDefaults:
[[NSUserDefaults standardUserDefaults]objectForKey:#"theArray"];
setting values from an array to UITableViewCell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"TheCell";
UITableViewCell *_cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (_cell == nil) {
_cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
_cell.textLabel.text = [yourArray objectAtIndex:indexPath.row];
return _cell;
}
Hope it helps
update
don't have a Mac nearby at the moment, so my answer might be a bit sloppy.
In your header file don't forget to add UITableViewDelegate and UITableViewDataSource, so it will look somewhat like that:
#interface yourController : UIViewController <UITableViewDelegate, UITableViewDataSource, ... some others if you need it ...> {
then in the implementation file(.m) you can just start typing
-tableview
and then use the autocompletion to get the methods that you need. You will most probably need these 3:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- (void)tableView: (UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath
depending on the needs of your app you might need more of them, but these 3 should be there.
For more info about UITableView please check that link: http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableView_Class/Reference/Reference.html

UITAbleView Giving Error

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//NSLog(#"Array: %#",rows);
return [rows count];// AT THIS LINE
}
Program received signal: “EXC_BAD_ACCESS”
THANKS FOR THE REPLY
Actually I have attached it to the WebPage By NSUrl where I have made a PHP array and I have created a NSLOG where I am getting the Values in the array form but When It exceute the line return [rows count];. It gives error when I am writting statically return 2; then it execute. I am explaining to you what I am doing. I am initialising the NIb with
Name tableViewController=[[JsonTestViewController alloc] initWithNibName:#"JsonTestViewController" bundle:nil];
In JsonTestViewController.m
I have this code:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//NSLog(#"Array: %#",rows);
return [rows count];
}
// Customize the appearance of table view cells.
- (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.
NSDictionary *dict = [rows objectAtIndex: indexPath.row];
NSString *strlb1=[dict objectForKey:#"block"];
NSString *strlb2=[dict objectForKey:#"name"];
strlb1=[strlb1 stringByAppendingString:#" , "];
strlb1=[strlb1 stringByAppendingString:strlb2];
NSString *str1=#"FPS : ";
NSString *str2=[dict objectForKey:#"p_hours"];
NSString *strpinf;
if([str2 isEqualToString:#"FP"])
{
strpinf=#"Free Parking";
}
else if([str2 isEqualToString:#"12"])
{
strpinf=#"2 hours";
}
else if([str2 isEqualToString:#"14"])
{
strpinf=#"4 hours";
}
else if([str2 isEqualToString:#"MP"])
{
strpinf=#"Metered Parking";
}
str1=[str1 stringByAppendingString:strpinf];
cell.textLabel.text =strlb1;
cell.detailTextLabel.text = str1;
return cell;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:#"SITE URL"];
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url];
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSError *error = nil;
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (dict)
{
rows = [dict objectForKey:#"users"];
}
NSLog(#"Array: %#",rows);
[jsonreturn release];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
can you give more info? This can be anything, but most likely, rows is pointing to memory where a valid array used to be. How did you create the rows array?
For example, your rows array or dictionary not longer pointing to valid memory if you created the rows array as an autoreleased object through a factory method in another method.
Here's another question that's pretty close to what you're describing:
EXC_BAD_ACCESS signal received
EDIT:
So looking at the code you provided, with these lines there are some possibilities:
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (dict) { rows = [dict objectForKey:#"users"]; }
the deserializeAsDictionary method can return either an autoreleased dictionary or NULL. so one possibility is that rows = NULL. when you try [rows count], your program will crash. Check and see what's in error, might give you some clues.
This will cause an error even when you explicitly return 2 for numberOfRowsInSection: because in cellForRowAtIndexPath:, you're still trying to access rows, even if it could possibly be NULL.
the other possibility lies in how you've defined rows. I'm guessing it's a property in your class. But where you have rows=[dict objectForKey:#"users"];, rows can point to nothing after the method's finished. Rows will still have the address of where [dict objectForKey:] was, but after the scope of the method, dict may be gone and all the data that comes with it.
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
under the KVC guidelines, you should expect dict to autorelease after the end of method.
and another possibility is, since i don't know the specifics of the JSON class you're using, is that when you release jsonreturn, you're also dealloc'ing all the data associated with it. So in effect, rows is pointing to nothing.
case in point, the error seems to be rooted in how you're setting/retaining/accessing rows.
try using the Build->Build&Analyze in xcode. it might give you some more hints. or throw in a bunch of NSLog(#"%d",[rows count]); all over. also try using the debugger. it'll give you a trace of method calls that lead up to [rows count] faulting.