I'm trying to parse RSS date to view in my app, following this tutorial. I have a JSON file to retrieve information from and display on the screen.
Here's the code
//
// ViewController.m
// JSONyt
//
// Created by yo_291 on 3/16/15.
// Copyright (c) 2015 yo_291. All rights reserved.
//
#import "ViewController.h"
#interface ViewController ()
{
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *array;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[[self myView]setDelegate:self];
[[self myView]setDataSource:self];
array = [[NSMutableArray alloc]init];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"fail with error");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary *rd = [allDataDictionary objectForKey:#"responseData"];
NSDictionary *feed = [rd objectForKey:#"feed"];
NSArray *aoe = [feed objectForKey:#"entries"];
for(NSDictionary *diction in aoe)
{
NSDictionary *numb = [diction objectForKey:#"0"];
NSString *title = [numb objectForKey:#"title"];
[array addObject:title];
}
[[self myView] reloadData];
}
- (IBAction)getFeed:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://ajax.googleapis.com/ajax/services/feed/load?v=2.0&q=http://www.britannica.com/feeds/tdih.rss&num="];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if(connection)
{
webData = [[NSMutableData alloc]init];
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellI = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellI];
if(!cell)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellI];
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
return cell;
}
#end
The application crashes on the line [array addObject:title];.
Error Stack trace:
2015-03-16 22:32:51.650 JSONyt[8195:547408] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
*** First throw call stack:
(
0 CoreFoundation 0x000000010ba28a75 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010b6c1bb7 objc_exception_throw + 45
2 CoreFoundation 0x000000010b8f70ca -[__NSArrayM insertObject:atIndex:] + 954
3 JSONyt 0x000000010b18da5f -[ViewController connectionDidFinishLoading:] + 735
4 CFNetwork 0x000000010d85998c __65-[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:]_block_invoke + 69
5 CFNetwork 0x000000010d859930 -[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:] + 199
6 CFNetwork 0x000000010d859a97 -[NSURLConnectionInternal _withActiveConnectionAndDelegate:] + 48
7 CFNetwork 0x000000010d729937 ___ZN27URLConnectionClient_Classic26_delegate_didFinishLoadingEU13block_pointerFvvE_block_invoke + 107
8 CFNetwork 0x000000010d7f6a31 ___ZN27URLConnectionClient_Classic18_withDelegateAsyncEPKcU13block_pointerFvP16_CFURLConnectionPK33CFURLConnectionClientCurrent_VMaxE_block_invoke_2 + 273
9 CFNetwork 0x000000010d714d16 _ZN19RunloopBlockContext13_invoke_blockEPKvPv + 72
10 CoreFoundation 0x000000010b930b44 CFArrayApplyFunction + 68
11 CFNetwork 0x000000010d714bd7 _ZN19RunloopBlockContext7performEv + 133
12 CFNetwork 0x000000010d714a16 _ZN17MultiplexerSource7performEv + 256
13 CFNetwork 0x000000010d71482c _ZN17MultiplexerSource8_performEPv + 72
14 CoreFoundation 0x000000010b95dc91 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
15 CoreFoundation 0x000000010b953b5d __CFRunLoopDoSources0 + 269
16 CoreFoundation 0x000000010b953194 __CFRunLoopRun + 868
17 CoreFoundation 0x000000010b952bc6 CFRunLoopRunSpecific + 470
18 GraphicsServices 0x000000010f005a58 GSEventRunModal + 161
19 UIKit 0x000000010be18580 UIApplicationMain + 1282
20 JSONyt 0x000000010b18e483 main + 115
21 libdyld.dylib 0x000000010dfd6145 start + 1
22 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
but I have no idea how to go about fixing it. To my eyes I'm searching the JSON file correctly but I may be wrong. The JSON file is also an RSS feed that I've used a google tool to "turn" into a JSON database, so I'm unsure if complications are from there.
Let me know any/all information that is needed, this is my first post so I don't know if I'm delivering enough context.
The error indicates that the object to be inserted is nil. The problem lies in the following lines:
NSDictionary *numb = [diction objectForKey:#"0"];
NSString *title = [numb objectForKey:#"title"];
[array addObject:title];
You never check whether title is nil or not before adding object to array. You can always use NSLog() to debug the values and check for nil values using techniques similar as follow:
if([numb objectForKey:#"title"] != nil) {
[array addObject:[numb objectForKey:#"title"]];
}
p.s. assigning the value to title is useless, as the title just used once (wasting memory).
Also, using libraries like AFNetworking will make your codes simpler, and provides extra error handling.
Related
I am trying to populate a table view with the file names of the files located in the documents directory but when the button is clicked to show the table view the app crashes saying that the object at index is 0. but there are 14 objects in the array. What could be the fault?
#implementation loadDataTVC
- (void)viewDidLoad {
[super viewDidLoad];
}
-(void) viewWillAppear:(BOOL)animated{
DataSource *sharedManager = [DataSource sharedManager];
NSString *documentDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
sharedManager.directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirectoryPath error:NULL];
NSLog(#"%lu", (unsigned long)[sharedManager.directoryContent count]);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
DataSource *sharedManager = [DataSource sharedManager];
NSString *documentDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
sharedManager.directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirectoryPath error:NULL];
if (sharedManager.directoryContent.count > 0) {
return (unsigned long)[sharedManager.directoryContent count];
}
else{
return 1;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"files" forIndexPath:indexPath];
DataSource *sharedManager = [DataSource sharedManager];
NSString *documentDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
sharedManager.directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirectoryPath error:NULL];
if (sharedManager.directoryContent.count > 0) {
cell.textLabel.text = [NSString stringWithFormat:#"%#", [sharedManager.directoryContent objectAtIndex:indexPath.row]];
}
else{
cell.textLabel.text = #"No data Available";
}
return cell;
}
The log:
2016-05-18 15:00:44.502 GeoData Grapher[4554:331076] 14
2016-05-18 15:00:47.412 GeoData Grapher[4554:331076] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'
*** First throw call stack:
(
0 CoreFoundation 0x000000010d2cdd85 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010cd41deb objc_exception_throw + 48
2 CoreFoundation 0x000000010d275885 -[__NSArray0 objectAtIndex:] + 101
3 GeoData Grapher 0x000000010a5f07d6 -[DeviceListTVC prepareForSegue:sender:] + 326
4 UIKit 0x000000010bcc95d5 -[UIStoryboardSegueTemplate _performWithDestinationViewController:sender:] + 369
5 UIKit 0x000000010bcc9433 -[UIStoryboardSegueTemplate _perform:] + 82
6 UIKit 0x000000010bcc96f7 -[UIStoryboardSegueTemplate perform:] + 156
7 UIKit 0x000000010b583a8d -[UIApplication sendAction:to:from:forEvent:] + 92
8 UIKit 0x000000010b991067 -[UIBarButtonItem(UIInternal) _sendAction:withEvent:] + 152
9 UIKit 0x000000010b583a8d -[UIApplication sendAction:to:from:forEvent:] + 92
10 UIKit 0x000000010b6f6e67 -[UIControl sendAction:to:forEvent:] + 67
11 UIKit 0x000000010b6f7143 -[UIControl _sendActionsForEvents:withEvent:] + 327
12 UIKit 0x000000010b6f72be -[UIControl _sendActionsForEvents:withEvent:] + 706
13 UIKit 0x000000010b6f6263 -[UIControl touchesEnded:withEvent:] + 601
14 UIKit 0x000000010b5f699f -[UIWindow _sendTouchesForEvent:] + 835
15 UIKit 0x000000010b5f76d4 -[UIWindow sendEvent:] + 865
16 UIKit 0x000000010b5a2dc6 -[UIApplication sendEvent:] + 263
17 UIKit 0x000000010b57c553 _UIApplicationHandleEventQueue + 6660
18 CoreFoundation 0x000000010d1f3301 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
19 CoreFoundation 0x000000010d1e922c __CFRunLoopDoSources0 + 556
20 CoreFoundation 0x000000010d1e86e3 __CFRunLoopRun + 867
21 CoreFoundation 0x000000010d1e80f8 CFRunLoopRunSpecific + 488
22 GraphicsServices 0x000000010eb7aad2 GSEventRunModal + 161
23 UIKit 0x000000010b581f09 UIApplicationMain + 171
24 GeoData Grapher 0x000000010a5f405f main + 111
25 libdyld.dylib 0x000000011253c92d start + 1
26 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
The Segue:
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NSIndexPath *selectedPath = [self.tableView indexPathForCell:sender];
AirconsoleDevice *selectedDevice = self.manager.defaultDevice;
if (selectedPath.section == 0) {
selectedDevice = self.currentDevices[selectedPath.row];
}
if ([segue.identifier isEqualToString:#"session_details"]) {
AirconsoleSession *session = [[AirconsoleSession alloc] initWithDevice:selectedDevice];
currentSession = session;
SessionDetailsVC *sdvc = segue.destinationViewController;
sdvc.session = session;
} else {
// we are presenting the Device Details
DeviceDetailsTVC *ddvc = [segue.destinationViewController viewControllers][0];
ddvc.device = selectedDevice;
}
}
The problem is in this line
DeviceDetailsTVC *ddvc = [segue.destinationViewController viewControllers][0];
ddvc.device = selectedDevice;
The destination controller is I assume a Navigation controller. And you are accessing the first controller in the stack.
Check this is actually set up correctly in the Storyboard. Because thats what the line of code expects, but the crash says it cannot find any member in the viewControllers array.
AFAIK it has nothing to do with the table view and 14 items.
Please help me with my school project, currently i suppose to retrieve a set of record from the database and display the record based on their category.
I am new to IOS programming so please help me.
If possible please explain to me what is my mistake and possible solution to solve it.
Sorry to be rude, i need the solution to solve it as soon as possible cause i also need to work on other part of the project.
LocationListTableViewController.m
#import "LocationListTableViewController.h"
#import <Parse/Parse.h>
#interface LocationListTableViewController ()
#property (strong, nonatomic) IBOutlet UITableView *testView;
#end
#implementation LocationListTableViewController {
NSArray *storeLocation;
NSMutableDictionary *categoriesDict;
NSString *checkValue;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
PFQuery *query = [PFQuery queryWithClassName:#"GPS"];
// pulling everything
UIActivityIndicatorView *ai = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
ai.center = self.view.center;
[ai startAnimating];
[self.view addSubview:ai];
storeLocation = [query findObjects];
[ai stopAnimating];
[self.tableView reloadData];
categoriesDict = [[NSMutableDictionary alloc]init];
for (NSDictionary *locationCat in storeLocation) {
NSString *stringLocation = [locationCat objectForKey:#"locationCategory"];
NSMutableSet *categoriesSet = [categoriesDict objectForKey:stringLocation];
if (!categoriesSet)
{
categoriesSet = [NSMutableSet set];
[categoriesDict setObject:categoriesSet forKey:[locationCat objectForKey:#"locationCategory"]];
}
[categoriesSet addObject:locationCat];
// NSLog(#"categroesDict value are %d", [[categoriesDict objectForKey:#"All"] count]);
// NSLog(#"categroesDict value are %#", [categoriesDict objectForKey:#"test"]);
};
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[categoriesDict objectForKey:checkValue] count];
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleid = #"Location";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleid];
if (cell == nil)
{
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:simpleid];
}
// NSLog(#"categoriesDict objectForKey:checkValue ---- %#", [categoriesDict objectForKey:checkValue]);
// NSLog(#"categoriesDict objectForKey:checkValue valueForKey ---- %#", [[categoriesDict objectForKey:checkValue]valueForKey:#"locationCategory"]);
// NSLog(#"categoriesDict objectForKey:checkValue valueForKey ---- %#", [[categoriesDict objectForKey:checkValue]valueForKey:#"locationName"]);
UILabel *locationLabel = (UILabel *)[cell viewWithTag:100];
locationLabel.text = [[categoriesDict objectForKey:checkValue]valueForKey:#"locationName"];
UILabel *addressLabel = (UILabel *)[cell viewWithTag:101];
addressLabel.text = [[categoriesDict objectForKey:checkValue]valueForKey:#"locationAddress"];
UIImageView *thumbnailImageView = (PFImageView *)[cell viewWithTag:102];
self.thumbnail= [[categoriesDict objectForKey:checkValue]valueForKey:#"locationImage"];
// NSLog(#"thumbnail is %#", self.thumbnail);
if (self.thumbnail == NULL)
{
thumbnailImageView.image= [UIImage imageNamed:#"placeholder.jpg"];
} else
{
//Got error occurred
[self.thumbnail getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
if (!error) {
UIImage *image = [UIImage imageWithData:imageData];
thumbnailImageView.image = image;
}
else{
NSLog(#"imageData value; %#", imageData);
}
}];
}
return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [categoriesDict count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
checkValue = [[categoriesDict allKeys]objectAtIndex:section];
return [[categoriesDict allKeys]objectAtIndex:section];
}
#end
Error Message
2015-01-14 15:27:36.658 MyLocationDemo[5591:60b] Warning: A long-running operation is being executed on the main thread.
Break on warnBlockingOperationOnMainThread() to debug.
2015-01-14 15:28:04.207 MyLocationDemo[5591:60b] -[__NSSetI getDataInBackgroundWithBlock:]: unrecognized selector sent to instance 0xaabed00
2015-01-14 15:28:04.208 MyLocationDemo[5591:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSSetI getDataInBackgroundWithBlock:]: unrecognized selector sent to instance 0xaabed00'
*** First throw call stack:
(
0 CoreFoundation 0x027711e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x024f08e5 objc_exception_throw + 44
2 CoreFoundation 0x0280e243 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
3 CoreFoundation 0x0276150b ___forwarding___ + 1019
4 CoreFoundation 0x027610ee _CF_forwarding_prep_0 + 14
5 MyLocationDemo 0x000030df -[LocationListTableViewController tableView:cellForRowAtIndexPath:] + 1199
6 UIKit 0x012a911f -[UITableView _createPreparedCellForGlobalRow:withIndexPath:] + 412
7 UIKit 0x012a91f3 -[UITableView _createPreparedCellForGlobalRow:] + 69
8 UIKit 0x0128aece -[UITableView _updateVisibleCellsNow:] + 2428
9 UIKit 0x0129f6a5 -[UITableView layoutSubviews] + 213
10 UIKit 0x0121f964 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 355
11 libobjc.A.dylib 0x0250282b -[NSObject performSelector:withObject:] + 70
12 QuartzCore 0x004ee45a -[CALayer layoutSublayers] + 148
13 QuartzCore 0x004e2244 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
14 QuartzCore 0x004e20b0 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 26
15 QuartzCore 0x004487fa _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
16 QuartzCore 0x00449b85 _ZN2CA11Transaction6commitEv + 393
17 QuartzCore 0x005075b0 +[CATransaction flush] + 52
18 UIKit 0x011ae9bb _UIApplicationHandleEventQueue + 13095
19 CoreFoundation 0x026fa77f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
20 CoreFoundation 0x026fa10b __CFRunLoopDoSources0 + 235
21 CoreFoundation 0x027171ae __CFRunLoopRun + 910
22 CoreFoundation 0x027169d3 CFRunLoopRunSpecific + 467
23 CoreFoundation 0x027167eb CFRunLoopRunInMode + 123
24 GraphicsServices 0x043555ee GSEventRunModal + 192
25 GraphicsServices 0x0435542b GSEventRun + 104
26 UIKit 0x011b0f9b UIApplicationMain + 1225
27 MyLocationDemo 0x0000391d main + 141
28 libdyld.dylib 0x02cba701 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
I'm trying to recreate a basic app by looking through the source code of the orignal app and learning it and then trying to retype into a separate file (and also making sure various parts in the Interface Builder match the original). One issue I'm having though is that I'm getting the following error:
2014-05-27 14:02:10.701 Nav Ctrl Practice[3513:60b] adding stock price: to company at index 1
2014-05-27 14:02:10.703 Nav Ctrl Practice[3513:60b] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]'
*** First throw call stack:
(
0 CoreFoundation 0x0000000101a3d495 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010179c99e objc_exception_throw + 43
2 CoreFoundation 0x00000001019e3745 -[__NSArrayM objectAtIndex:] + 213
3 Nav Ctrl Practice 0x0000000100003ad2 -[ParentViewController connectionDidFinishLoading:] + 530
4 Foundation 0x000000010148d36b __65-[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:]_block_invoke + 48
5 Foundation 0x0000000101340bdb -[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:] + 210
6 Foundation 0x0000000101340aec -[NSURLConnectionInternal _withActiveConnectionAndDelegate:] + 69
7 CFNetwork 0x0000000106950637 ___ZN27URLConnectionClient_Classic26_delegate_didFinishLoadingEU13block_pointerFvvE_block_invoke + 107
8 CFNetwork 0x000000010694e802 ___ZN27URLConnectionClient_Classic18_withDelegateAsyncEPKcU13block_pointerFvP16_CFURLConnectionPK33CFURLConnectionClientCurrent_VMaxE_block_invoke_2 + 84
9 CoreFoundation 0x00000001019e3f74 CFArrayApplyFunction + 68
10 CFNetwork 0x00000001068c13e7 _ZN19RunloopBlockContext7performEv + 133
11 CFNetwork 0x00000001068c1217 _ZN17MultiplexerSource7performEv + 247
12 CFNetwork 0x00000001068c103a _ZN17MultiplexerSource8_performEPv + 72
13 CoreFoundation 0x00000001019ccd21 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
14 CoreFoundation 0x00000001019cc5f2 __CFRunLoopDoSources0 + 242
15 CoreFoundation 0x00000001019e846f __CFRunLoopRun + 767
16 CoreFoundation 0x00000001019e7d83 CFRunLoopRunSpecific + 467
17 GraphicsServices 0x0000000103bb4f04 GSEventRunModal + 161
18 UIKit 0x0000000100349e33 UIApplicationMain + 1010
19 Nav Ctrl Practice 0x0000000100005eb3 main + 115
20 libdyld.dylib 0x0000000101fc25fd start + 1
21 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
I found a couple links on this site relating to the error shown above ("terminating with uncaught exception of type NSException"), however none of the specific causes seemed to match mine. The code I'm using is completely copied from a working file. So I'm not sure what I'm missing here. I've included below the source for the section where it appears to have an issue with the array.
//
// ParentViewController.m
//
#import "ParentViewController.h"
#import "ChildViewController.h"
#import "DataAccess.h"
#import "sqlite3.h"
#interface ParentViewController ()
{
NSMutableArray *arrayOfProducts;
NSMutableArray *arrayOfCompanies;
sqlite3 *productDB;
sqlite3 *companyDB;
}
#end
#implementation ParentViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
arrayOfProducts = [[NSMutableArray alloc] init];
[[self myTableView]setDelegate:self];
[[self myTableView]setDataSource:self];
self.dataAccess = [[DataAccess alloc] init];
[self.dataAccess setCompanyListFromDB];
self.childVC = [[ChildViewController alloc] init];
NSMutableString *urlQuotes = [NSMutableString stringWithString:#"http://download.finance.yahoo.com/d/quotes.csv?s="];
for(int i =0; i<self.dataAccess.companyList.count; i++) {
Company *company = self.dataAccess.companyList[i];
[urlQuotes appendFormat:#"%#", company.stockSymbol];
if(i<self.dataAccess.companyList.count-1)
{ [urlQuotes appendString:#","];
}
[urlQuotes appendString:#"&f=l1,"];
NSLog(#"Quote URL: %#", urlQuotes);
_responseData =[[NSMutableData alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:urlQuotes]] ; //we are creating the request here
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; //we are creating the url connection and firing the request here
[conn start]; //start the connection
}
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSLog(#"numberOfSectionsInTableView");
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"numberOfRowsInSection");
return [self.dataAccess.companyList 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:#"UITableViewCell"];
}
int row = indexPath.row;
NSLog(#"Cell at index: %d", row);
//Find the company for this row in the table
Company * company = self.dataAccess.companyList[row];
NSLog(#"Got company %# at index: %d from companyList Array", company.name, row);
// Configure the cell...
//make the row's text be the company's name
cell.textLabel.text = company.name;
[[cell imageView] setImage: [UIImage imageNamed: company.logo]];
cell.detailTextLabel.text = company.stockPrice;
return cell;
}
#pragma mark - Table view delegate
// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int row = indexPath.row;
NSLog(#"Cell at index: %d", row);
self.childVC.company = self.dataAccess.companyList[row];
// [self.dataAccess test];
self.childVC.dataAccess2 = self.dataAccess;
[self.navigationController pushViewController:self.childVC animated:YES];
}
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to the instance variable you declared
[_responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *str = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSMutableArray *responseArray= [NSMutableArray arrayWithArray: [str componentsSeparatedByString:#"\n"] ];
//includes extra blank character at the end; just leaving it there for now
NSLog(#"Response Array: %#", responseArray);
for(int i=0;i<[self.dataAccess.companyList count];i++){
Company *company = self.dataAccess.companyList[i];
NSMutableString *string = responseArray[i];
NSLog(#"adding stock price: %# to company at index %d", string, i);
company.stockPrice = string;
} //simple loop for referring to items in companyList
[self.tableView reloadData];
NSLog (#"connectionDidFinishLoading Done");
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog (#"connection didFailWithError: %#", error.debugDescription);
}
#end
The problem appears to be in your implementation of connectionDidFinishLoading:.
for(int i=0;i<[self.dataAccess.companyList count];i++){
Company *company = self.dataAccess.companyList[i];
NSMutableString *string = responseArray[i];
...
}
Here, you use the same iterator variable (i) for both companyList and responseArray, even though they are different sizes. You should ensure that i is less than the length of both responseArray and companyList:
for(int i=0;i<[self.dataAccess.companyList count] && i<[responseArray count];i++){
Company *company = self.dataAccess.companyList[i];
NSMutableString *string = responseArray[i];
...
}
Help!
I am new to XCode and now i am facing a problem.
When i use the following code in the app and create a new ViewController class LoginViewController.
In iPhone, the app work great. But when I test in iPad it crash and display the following content in the log:
2014-05-06 17:05:31.289 We Love HK[38711:60b] -[LoginViewController viewControllers]: unrecognized selector sent to instance 0x10942c3d0
2014-05-06 17:05:31.291 We Love HK[38711:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[LoginViewController viewControllers]: unrecognized selector sent to instance 0x10942c3d0'
*** First throw call stack:
(
0 CoreFoundation 0x00000001019fc495 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010175b99e objc_exception_throw + 43
2 CoreFoundation 0x0000000101a8d65d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x00000001019edd8d ___forwarding___ + 973
4 CoreFoundation 0x00000001019ed938 _CF_forwarding_prep_0 + 120
5 We Love HK 0x0000000100001086 -[AppDelegate application:didFinishLaunchingWithOptions:] + 246
6 UIKit 0x00000001003033d9 -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 264
7 UIKit 0x0000000100303be1 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1605
8 UIKit 0x0000000100307a0c -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 660
9 UIKit 0x0000000100318d4c -[UIApplication handleEvent:withNewEvent:] + 3189
10 UIKit 0x0000000100319216 -[UIApplication sendEvent:] + 79
11 UIKit 0x0000000100309086 _UIApplicationHandleEvent + 578
12 GraphicsServices 0x0000000103b2b71a _PurpleEventCallback + 762
13 GraphicsServices 0x0000000103b2b1e1 PurpleEventCallback + 35
14 CoreFoundation 0x000000010197e679 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 41
15 CoreFoundation 0x000000010197e44e __CFRunLoopDoSource1 + 478
16 CoreFoundation 0x00000001019a7903 __CFRunLoopRun + 1939
17 CoreFoundation 0x00000001019a6d83 CFRunLoopRunSpecific + 467
18 UIKit 0x00000001003072e1 -[UIApplication _run] + 609
19 UIKit 0x0000000100308e33 UIApplicationMain + 1010
20 We Love HK 0x00000001000044b3 main + 115
21 libdyld.dylib 0x000000010207f5fd start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
And LoginViewController.h:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "KeychainItemWrapper.h"
#import Security;
#interface LoginViewController : UIViewController <UITextFieldDelegate>
#property (nonatomic, retain) IBOutlet UILabel *version_label;
#property (strong, nonatomic) IBOutlet UITextField *txtUsername;
#property (strong, nonatomic) IBOutlet UITextField *txtPassword;
- (IBAction) loginClicker:(id)sender;
- (IBAction) backgroundTap:(id)sender;
- (IBAction) keyboardDismiss: (id) sender;
- (IBAction) click_exit: (id) sender;
#end
LoginViewController.m:
#import "LoginViewController.h"
#implementation LoginViewController;
#synthesize version_label;
#synthesize txtUsername;
#synthesize txtPassword;
-(void)viewDidLoad
{
KeychainItemWrapper *keychainWrapper = [[KeychainItemWrapper alloc] initWithIdentifier:#"UserAuthToken" accessGroup:nil];
NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleShortVersionString"]; // Get App Version
NSString *build = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleVersion"]; // Get App Build Number
version_label.numberOfLines = 0; // Enable \n break line
version_label.hidden = NO; // Disable Hidden
//[keychainWrapper resetKeychainItem];
version_label.text = [NSString stringWithFormat:#"V %# (Build %#)", version, build]; // Change Version Label's Content
if ([keychainWrapper objectForKey:(__bridge id)(kSecAttrAccount)] && [keychainWrapper objectForKey:(__bridge id)(kSecValueData)]){
txtUsername.text = [keychainWrapper objectForKey:(__bridge id)(kSecAttrAccount)];
txtPassword.text = [keychainWrapper objectForKey:(__bridge id)(kSecValueData)];
}
}
-(IBAction) keyboardDismiss: (id) sender{
[txtUsername resignFirstResponder];
[txtPassword resignFirstResponder];
}
- (IBAction)backgroundTap:(id)sender {
[txtUsername resignFirstResponder];
[txtPassword resignFirstResponder];
}
- (IBAction)click_exit:(id)sender {
//[txtUsername resignFirstResponder];
//[txtPassword resignFirstResponder];
}
- (IBAction)loginClicker:(id)sender {
NSInteger success = 0;
#try {
if([[self.txtUsername text] isEqualToString:#""] || [[self.txtPassword text] isEqualToString:#""] ) {
[self alertStatus:#"請輸入帳號及密碼!" :#"登入失敗!" :0];
} else {
KeychainItemWrapper *keychainWrapper = [[KeychainItemWrapper alloc] initWithIdentifier:#"UserAuthToken" accessGroup:nil];
NSString *post =[[NSString alloc] initWithFormat:#"username=%#&password=%#",[self.txtUsername text],[self.txtPassword text]];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"http://ls.arefly.com/other/php/welovehk/login.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
success = [jsonData[#"login_status"] integerValue];
NSLog(#"Success: %ld", (long)success);
if(success == 1)
{
NSLog(#"Login SUCCESS");
[keychainWrapper setObject:[self.txtUsername text] forKey:(__bridge id)(kSecAttrAccount)];
[keychainWrapper setObject:[self.txtPassword text] forKey:(__bridge id)(kSecValueData)];
NSString *name_msg = (NSString *) jsonData[#"name_msg"];
[self alertStatus:name_msg :#"歡迎!" :0];
} else {
NSString *error_msg = (NSString *) jsonData[#"error_message"];
[self alertStatus:error_msg :#"登入失敗!" :0];
txtPassword.text = #"";
}
} else {
//if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Connection Failed" :#"登入失敗!" :0];
txtPassword.text = #"";
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"登入失敗!" :#"錯誤:" :0];
txtPassword.text = #"";
}
if (success) {
[self performSegueWithIdentifier:#"login_success" sender:self];
}
}
- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
alertView.tag = tag;
[alertView show];
}
#end
and here also didFinishLaunchingWithOptions in AppDelegate.m (but i do not think i change anything of it):
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
splitViewController.delegate = (id)navigationController.topViewController;
}
return YES;
}
and here is my Main_iPad.storyboard:
http://uploadpie.com/rTIVc
and here is my Main_iPhone.storyboard:
http://uploadpie.com/gmpms
Can any one help me?
Thanks!
UPDATE
After i comment the whole if block in -(BOOL)application:didFinishLaunchingWithOptions:, its become ok and do not crash.
But there are other crash appear when i want to do [self performSegueWithIdentifier:#"login_success" sender:self];
2014-05-06 18:55:28.839 We Love HK[45660:60b] Success: 1
2014-05-06 18:55:28.839 We Love HK[45660:60b] Login SUCCESS
2014-05-06 18:55:28.887 We Love HK[45660:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present a Split View Controllers modally <LoginViewController: 0x109429ca0>.'
*** First throw call stack:
(
0 CoreFoundation 0x00000001019fc495 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010175b99e objc_exception_throw + 43
2 UIKit 0x0000000100408c93 -[UIViewController presentViewController:withTransition:completion:] + 4027
3 We Love HK 0x0000000100005a35 -[LoginViewController loginClicker:] + 3813
4 UIKit 0x0000000100309f06 -[UIApplication sendAction:to:from:forEvent:] + 80
5 UIKit 0x0000000100309eb4 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 17
6 UIKit 0x00000001003e6880 -[UIControl _sendActionsForEvents:withEvent:] + 203
7 UIKit 0x00000001003e595d -[UIControl touchesBegan:withEvent:] + 219
8 UIKit 0x0000000100340b74 -[UIWindow _sendTouchesForEvent:] + 300
9 UIKit 0x00000001003416e4 -[UIWindow sendEvent:] + 925
10 UIKit 0x000000010031929a -[UIApplication sendEvent:] + 211
11 UIKit 0x0000000100306aed _UIApplicationHandleEventQueue + 9579
12 CoreFoundation 0x000000010198bd21 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
13 CoreFoundation 0x000000010198b5f2 __CFRunLoopDoSources0 + 242
14 CoreFoundation 0x00000001019a746f __CFRunLoopRun + 767
15 CoreFoundation 0x00000001019a6d83 CFRunLoopRunSpecific + 467
16 GraphicsServices 0x0000000103b29f04 GSEventRunModal + 161
17 UIKit 0x0000000100308e33 UIApplicationMain + 1010
18 We Love HK 0x00000001000045b3 main + 115
19 libdyld.dylib 0x000000010207f5fd start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
Also i want to know how can i set the splitViewController.delegate from a different place?
You should propably share your application:didFinishLaunchingWithOptions: method.
I am pretty sure that somewhere there you are using LoginViewController is used as UINavigationController or UISplitViewController. That is why viewControllers method is called there.
According to your application:didFinishLaunchingWithOptions method, it crashes here
UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
Probably you have wrong InitialViewController in your iPad storyboard
The exception clearly states that
[LoginViewController viewControllers]: unrecognized selector sent to
instance
mean, the controller which is not present in the UIStoryBoard of iPad.
their will be 2 storyBoards in the project,
In iPhone, the app work great.
So mean, you have created LoginViewController for only iPhone not for iPad's storyBoard.
you need to create the LoginViewController in the iPad storyBoard as well.
each time i try and click on the search bar, the app keeps crashing, below is the code for the UItableview used with the parse.com SDK, is there something i missed on the code. its crashing when the search bar is clicked, before the keyboard gets loaded.
#
NSRangeException', reason: ' -[NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array' ** First throw call stack: ( 0 CoreFoundation 0x0000000102cb1795 __exceptionPreprocess + 165 1 libobjc.A.dylib 0x0000000102a14991 objc_exception_throw + 43 2 CoreFoundation
#
this is the view did load method to load search bar
#interface CarTableViewController () <UISearchDisplayDelegate, UISearchBarDelegate>
{
GADBannerView *bannerView_;
}
# property (nonatomic, strong) UISearchBar * searchbar;
# property (nonatomic, strong) UISearchDisplayController *searchcontroller;
# property (nonatomic, strong) NSMutableArray * SearchResults;
#end
#implementation CarTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//search bar
self.searchbar = [[UISearchBar alloc] initWithFrame: CGRectMake (0, 0, self.view.frame.size.width, 44)];
self.tableView.tableHeaderView = self.searchbar;
self.searchcontroller = [[UISearchDisplayController alloc] initWithSearchBar: self.searchbar contentsController: self];
self.searchcontroller.searchResultsDataSource = self;
self.searchcontroller.searchResultsDelegate = self;
self.searchcontroller.delegate = self;
CGPoint offset = CGPointMake(0, self.searchbar.frame.size.height);
self.tableView.contentOffset = offset;
self.searchResults = [NSMutableArray array];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
this is the load for parse
- (id)initWithCoder:(NSCoder *)aCoder
{
self = [super initWithCoder:aCoder];
if (self) {
self.parseClassName = #"movienow";
self.textKey = #"mName";
self.pullToRefreshEnabled = YES;
self.paginationEnabled = NO;
}
return self;
}
//where to search and other
- (void) filterResults: (NSString *)searchTerm{
[self.SearchResults removeAllObjects];
PFQuery * query = [PFQuery queryWithClassName: self.parseClassName]; // table in which you are looking for
[query whereKeyExists: # "mName"]; // column which you are looking for
[query whereKey: # "mName" containsString : searchTerm];
NSArray * results = [query findObjects];
[self.SearchResults addObjectsFromArray: results];
}
- (BOOL) searchDisplayController:(UISearchDisplayController *) controller shouldReloadTableForSearchString: (NSString *) searchstring {
[self filterResults: searchstring];
return YES;
}
- (NSInteger) Tableview: (UITableView *) Tableview numberOfRowsInSection: (NSInteger) section {
if (Tableview == self.tableView) {
return self.objects.count;
} else {
return self.SearchResults.count;
}
}
- (void) callbackLoadObjectsFromParse: (NSArray *)result error:(NSError *) error {
if (!error) {
[self.SearchResults removeAllObjects],
[self.SearchResults addObjectsFromArray: result];
[self.searchDisplayController.searchResultsTableView reloadData];
} else {
NSLog (# "Error:%# %#", error, [error userInfo]);
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
static NSString *CellIdentifier = #"CarTableCell";
CarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CarTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
if (tableView == self.tableView) {
//cell.mName.text = [object objectForKey:#"objectld"];
NSLog(#"%#",[object objectForKey:#"mName"]);
}
else if (tableView == self.searchDisplayController.searchResultsTableView){
PFObject *searchUser = [self.SearchResults objectAtIndex:indexPath.row];
NSLog(#"%#",[searchUser objectForKey:#"mName"]);
}
// Configure the cell...
return cell;
}
crash log
2014-01-23 15:58:23.440 MovieTimeLK2[8442:70b] * Terminating app due to uncaught exception 'NSRangeException', reason: ' -[NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
** First throw call stack:
(
0 CoreFoundation 0x0000000102cb1795 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000102a14991 objc_exception_throw + 43
2 CoreFoundation 0x0000000102c578e5 -[__NSArrayM objectAtIndex:] + 213
3 MovieTimeLK2 0x0000000100005aab -[CarTableViewController tableView:cellForRowAtIndexPath:object:] + 2155
4 MovieTimeLK2 0x0000000100078c7d -[PFQueryTableViewController tableView:cellForRowAtIndexPath:] + 200
5 UIKit 0x0000000101742b8a -[UITableView _createPreparedCellForGlobalRow:withIndexPath:] + 348
6 UIKit 0x000000010172a836 -[UITableView _updateVisibleCellsNow:] + 2297
7 UIKit 0x000000010173b381 -[UITableView layoutSubviews] + 207
8 UIKit 0x00000001016d2b27 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 354
9 QuartzCore 0x00000001010c7a22 -[CALayer layoutSublayers] + 151
10 QuartzCore 0x00000001010bc589 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 363
11 UIKit 0x00000001016c7470 -[UIView(Hierarchy) layoutBelowIfNeeded] + 521
12 UIKit 0x00000001019a46c3 -[UISearchDisplayControllerContainerView setFrame:] + 113
13 UIKit 0x000000010199de5f -[UISearchDisplayController setActive:animated:] + 9697
14 UIKit 0x00000001019a0576 -[UISearchDisplayController searchBarTextDidBeginEditing:] + 277
15 UIKit 0x00000001018e31b0 -[UISearchBar(UISearchBarStatic) _searchFieldBeginEditing] + 97
16 UIKit 0x00000001016780ae -[UIApplication sendAction:to:from:forEvent:] + 104
17 UIKit 0x0000000101678044 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 17
18 UIKit 0x000000010174c450 -[UIControl _sendActionsForEvents:withEvent:] + 203
19 UIKit 0x0000000101c83594 -[UITextField willAttachFieldEditor:] + 576
20 UIKit 0x00000001017513d7 -[UIFieldEditor becomeFieldEditorForView:] + 725
21 UIKit 0x0000000101c7b2df -[UITextField _becomeFirstResponder] + 143
22 UIKit 0x00000001018e5eb3 -[UISearchBarTextField _becomeFirstResponder] + 92
23 UIKit 0x000000010179fc0c -[UIResponder becomeFirstResponder] + 340
24 UIKit 0x00000001016c6abc -[UIView(Hierarchy) becomeFirstResponder] + 99
25 UIKit 0x0000000101c7ae53 -[UITextField becomeFirstResponder] + 51
26 UIKit 0x000000010198820c -[UITextInteractionAssistant(UITextInteractionAssistant_Internal) setFirstResponderIfNecessary] + 118
27 UIKit 0x0000000101989fc0 -[UITextInteractionAssistant(UITextInteractionAssistant_Internal) oneFingerTap:] + 1768
28 UIKit 0x000000010198050a _UIGestureRecognizerSendActions + 188
29 UIKit 0x000000010197f470 -[UIGestureRecognizer updateGestureWithEvent:buttonEvent:] + 357
30 UIKit 0x0000000101983829 __UIGestureRecognizerUpdate_block_invoke + 53
31 UIKit 0x00000001019837b1 _UIGestureRecognizerRemoveObjectsFromArrayAndApplyBlocks + 257
32 UIKit 0x000000010197b87d _UIGestureRecognizerUpdate + 93
33 UIKit 0x00000001016ac925 -[UIWindow _sendGesturesForEvent:] + 928
34 UIKit 0x00000001016ad5e5 -[UIWindow sendEvent:] + 910
35 UIKit 0x0000000101686fa2 -[UIApplication sendEvent:] + 211
36 UIKit 0x0000000101674d7f _UIApplicationHandleEventQueue + 9549
37 CoreFoundation 0x0000000102c40ec1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 17
38 CoreFoundation 0x0000000102c40792 __CFRunLoopDoSources0 + 242
39 CoreFoundation 0x0000000102c5c61f __CFRunLoopRun + 767
40 CoreFoundation 0x0000000102c5bf33 CFRunLoopRunSpecific + 467
41 GraphicsServices 0x00000001049873a0 GSEventRunModal + 161
42 UIKit 0x0000000101677043 UIApplicationMain + 1010
43 MovieTimeLK2 0x0000000100006c33 main + 115
44 libdyld.dylib 0x00000001035e65fd start + 1
45 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
From the crash log posted, it seems that your problem is in PFObject *searchUser = [self.SearchResults objectAtIndex:indexPath.row];
But that would be strange if you already use return self.SearchResults.count; in - (NSInteger) Tableview: (UITableView *) Tableview numberOfRowsInSection: (NSInteger) section
The first thing that comes to my mind is where you call [self.SearchResults removeAllObjects]; in - (void) filterResults: (NSString *)searchTerm , I suggest using the below code:
- (void) filterResults: (NSString *)searchTerm{
PFQuery * query = [PFQuery queryWithClassName: self.parseClassName]; // table in which you are looking for
[query whereKeyExists: # "mName"]; // column which you are looking for
[query whereKey: # "mName" containsString : searchTerm];
NSArray * results = [query findObjects];
self.SearchResults = [results mutableCopy];
}
Update:
Since it crashes with the first typing, then make sure that numberOfRowsInSection returns self.SearchResults.count not self.objects.count, if it does but doesn't return zero, try replacing self.searchResults = [NSMutableArray array]; with self.searchResults = [[NSMutableArray alloc] init]; in your viewDidLoad
Hope it solves your issue.
I think you don't initializate the mutable array change
self.searchResults = [NSMutableArray array];
to
self.searchResults = [NSMutableArray alloc]init];