Getting '-[__NSArrayM city]: unrecognized selector sent to instance 0x111c03460' error - ios

I'm trying to use Google's geocoding api to get the city name and geolocation. But I'm getting this error and don't know which part I go wrong. Could anyone please help?
Here's my code:
ViewController:
- (void)searchCityGeoLocationByName:(NSString *)name
{
[self.searchResults removeAllObjects];
NSString *requestUrl = [[NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true&key=%#", name, GOOGLE_GEOCODING_API_KEY] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:requestUrl
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)operation.response;
if (httpResponse.statusCode == 200) {
dispatch_async(dispatch_get_main_queue(), ^{
NSMutableArray *results = [NSMutableArray array];
for (id response in [responseObject objectForKey:#"results"]) {
self.search = [[Search alloc] initWithDictionary:response];
[results addObject:self.search];
}
self.searchResults = [NSMutableArray arrayWithCapacity:results.count];
for (int i = 0; i < results.count; i++) {
[self.searchResults addObject:results];
}
[self.searchController.searchResultsTableView reloadData];
});
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"SearchCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Search *search = [self.searchResults objectAtIndex:indexPath.row];
cell.textLabel.text = search.city;
return cell;
}
Search.h:
#interface Search : NSDictionary
- (id)initWithDictionary:(NSDictionary *)otherDictionary;
#property (nonatomic, strong) NSString *city;
#property (nonatomic, strong) NSString *lat;
#property (nonatomic, strong) NSString *lng;
#end
Search.m:
- (id)initWithDictionary:(NSDictionary *)otherDictionary
{
self = [super init];
if (self) {
self.city = [otherDictionary objectForKey:#"formatted_address"];
self.lat = [[otherDictionary valueForKeyPath:#"geometry.location"] objectForKey:#"lat"];
self.lng = [[otherDictionary valueForKeyPath:#"geometry.location"] objectForKey:#"lng"];
}
return self;
}
Thanks for your help.

Change this:
for (int i = 0; i < results.count; i++) {
[self.searchResults addObject:results];
}
to:
for (int i = 0; i < results.count; i++) {
[self.searchResults addObject:results[i]];
}
you adding array to self.searchResults and try to get Search object.

Replace
self.searchResults = [NSMutableArray arrayWithCapacity:results.count];
for (int i = 0; i < results.count; i++) {
[self.searchResults addObject:results];
}
With:
self.searchResults = results;
You can also just remove the results variable and use directly the self.searchResults variable instead.

When you are adding objects to self.searchResults you are adding the NSMutableArray results each time, so then in cellForRowAtIndexPath: when you try to assign search to:
Search *search = [self.searchResults objectAtIndex:indexPath.row];
Instead you are returning an NSMutableArray, so on the next line, when you try to access the search.city the object is an array, rather than a Search object.
You need to look at whether these lines are correct:
for (int i = 0; i < results.count; i++) {
[self.searchResults addObject:results];
}
Are you sure you want to be adding results there? Is an NSMutableArray of NSMutableArrays what you want self.searchResults to contain?
You probably want to replace it with something like this:
[self.searchResults addObject:results[i]];

Related

iOS: why second section is not displayed in UITableView?

My .h file :
#interface ViewPrescriptionViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
#property(weak, nonatomic) NSArray *arr;
#property (nonatomic, retain) NSArray *menuItems;
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property (nonatomic, retain) NSArray *medicineItems;
#end
My .m file :
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
/* Here i send parameter to server using AFNetworking, and i got response from server ,
menu_itemes: (
{
bp = "000/000";
dateTime = "05/12/2016 01:02:59 PM";
doc = {
"email_id" = "batra#gmail.com";
exception = 0;
gender = Male;
id = 0;
"mobile_no" = 1234567890;
name = Batra;
"profile_id" = 0;
qualification = "MD(Doctor)";
"reg_id" = 157;
salutation = Mr;
"wellness_id" = 251215782521;
};
"follow_up" = 17;
id = 37;
medicine = (
"Syrup,Decold Total,20,0-0-1,Before Meal,1",
"Injection,Insulin,1,0-0-1,Before Meal,1",
no,
no,
no,
no,
no,
no,
no,
no
);
patient = {
"email_id" = "bishtrohit#gmail.com";
exception = 0;
gender = Male;
id = 0;
"mobile_no" = 1234567890;
name = Rohit;
"profile_id" = 0;
qualification = "";
"reg_id" = 150;
salutation = Mr;
"wellness_id" = 290119935030;
};
weight = 000;
}
)
*/
[manager POST:Loginurl parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"Response from view Prescription server : %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
// menuItems=#[#"%#",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]];
NSArray *ResponseArray = [NSJSONSerialization JSONObjectWithData: responseObject options: kNilOptions error: nil];
if (ResponseArray.count >0)
{
self.menuItems = [[NSMutableArray alloc]initWithArray:ResponseArray];
[_tableView reloadData];
//menuItems = [ResponseArray mutableCopy];
NSLog(#"menu_itemes: %#",self.menuItems);
}
NSMutableArray *Myarray = [NSMutableArray new];
for (int i=0; i<_menuItems.count; i++) {
[Myarray addObject:[[_menuItems objectAtIndex:i] objectForKey:#"medicine"]];
NSLog(#"medicine: %#",Myarray);
}
if (Myarray.count>0) {
self.medicineItems=[NSArray arrayWithArray:Myarray];
//[_tableView reloadData];
NSLog(#"medicine items : %#",self.medicineItems);
NSLog(#"medicine items count : %lu",(unsigned long)self.medicineItems.count);
}
// _arr=[NSArray arrayWithArray:ResponseArray];
// NSLog(#"menu_itemes: %#",_menuItems);
[self getdata:responseObject];
} failure:^(NSURLSessionTask *operation, NSError *error)
{
......
Then
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0)
{
return 1;
}
else
{
NSLog(#"S");
//here is breakpoint
return self.medicineItems.count;
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0)
{
NSDictionary *content = [self.menuItems objectAtIndex:indexPath.row];
NSLog(#"content = %#",content);
ViewPrescriptionTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:#"PatientDetail" forIndexPath:indexPath];
[cell.datetime setText:[content valueForKey:#"dateTime"]];
[cell.bp setText:[content valueForKey:#"bp"]];
[cell.weight setText:[content valueForKey:#"weight"]];
[cell.followup setText:[content valueForKey:#"follow_up"]];
[cell.doctorname setText:[[content objectForKey:#"doc"]valueForKey:#"name"]];
[cell.mobile setText:[NSString stringWithFormat:#"%#",[[content objectForKey:#"doc"]valueForKey:#"mobile_no"]]];
[cell.email setText:[[content objectForKey:#"doc"]valueForKey:#"email_id"]];
[cell.qualification setText:[[content objectForKey:#"doc"]valueForKey:#"qualification"]];
[cell.wellnessid setText:[[content objectForKey:#"doc"]valueForKey:#"wellness_id"]];
[cell.patientname setText:[[content objectForKey:#"patient"]valueForKey:#"name"]];
[cell.patientmobile setText:[NSString stringWithFormat:#"%#",[[content objectForKey:#"patient"]valueForKey:#"mobile_no"]]];
[cell.patientemail setText:[[content objectForKey:#"patient"]valueForKey:#"email_id"]];
[cell.patientwellnessid setText:[[content objectForKey:#"patient"]valueForKey:#"wellness_id"]];
return cell;
}
else{
//Cell For Medicines
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:#"PatientDetail" forIndexPath:indexPath];
NSLog(#"s");
//here is breakpoint
[cell.textLabel setText:[self.medicineItems objectAtIndex:indexPath.row]];
return cell;
}
}
In Storyboard
I have taken UITableView on screen for this.
I have taken 1 static custom cell for this.
What i want :
I want two section, in first, i displayed all data which i receive from server except medicinItems like following image:
In second section,
I want to pass medicinItems in that.
but my problem is, second section is not displaped.
But i don't know how to do that..??
Please anyone can solve my issue. help will be appreciable.
You need to reload data after fetching from server and updating medicineItems:
if (Myarray.count>0) {
self.medicineItems=[NSArray arrayWithArray:Myarray];
dispatch_async(dispatch_get_main_queue(), ^{
[_tableView reloadData];
});
}
Furthermore:
[cell.textLabel setText:[self.medicineItems objectAtIndex:indexPath.row]];
self.medicineItems is not an array of strings in this case so you can't set the textLabel to that object

NSSortDescriptor doesn't update UITableView

I'm trying to sort my tableview using NSSortDescriptor in a UISegmentedControl. When I log the Array to sort it shows the correct sorting order, but the tableview doesn't update after calling [self.tableView reloadData];
The data comes from an array which is populated by a json feed. I'm not using NSObjects to display the tableview, it's all populated from the NSArray. See code below:
#interface LinksTableViewController (){
NSArray *data;
}
#property (strong, nonatomic) NSArray *links;
#property (strong, nonatomic) NSArray *tNames;
#property (strong, nonatomic) NSArray *dThor;
#property (strong, nonatomic) NSArray *theLinker;
#property (strong, nonatomic) NSArray *anText;
#property (strong, nonatomic) NSArray *noDo;
#end
#implementation LinksTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
UISegmentedControl *statFilter = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:#"STAT1", #"STAT2", #"STAT3", #"STAT4", nil]];
[statFilter sizeToFit];
[statFilter addTarget:self action:#selector(MySegmentControlAction:) forControlEvents: UIControlEventValueChanged];
self.navigationItem.titleView = statFilter;
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(refreshdelay:) userInfo:nil repeats:NO];
}
- (void)MySegmentControlAction:(UISegmentedControl *)segment
{
NSArray *arrayToSort = data;
if (segment.selectedSegmentIndex == 0)
{
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"pda" ascending:NO];
arrayToSort = [arrayToSort sortedArrayUsingDescriptors:#[sortDescriptor]];
NSLog(#"%#", arrayToSort);
}
else if (segment.selectedSegmentIndex == 1)
{
}
else if (segment.selectedSegmentIndex == 2)
{
}
else if (segment.selectedSegmentIndex == 3)
{
}
[self.tableView reloadData];
}
-(void)refreshdelay:(NSTimer*)timer
{
NSString *myString = [links absoluteString];
NSURL *JSONData = [NSURL URLWithString:myString];
NSData *datas = [NSData dataWithContentsOfURL:JSONData];
NSURLRequest *request = [NSURLRequest requestWithURL:JSONData];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
operation.responseSerializer.acceptableContentTypes = [operation.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:datas options:kNilOptions error:nil];
data = jsonResult;
NSMutableArray *names = [NSMutableArray array];
NSMutableArray *bLinks = [NSMutableArray array];
NSMutableArray *daThor = [NSMutableArray array];
NSMutableArray *bsLink = [NSMutableArray array];
NSMutableArray *ancTxt = [NSMutableArray array];
NSMutableArray *folLowd = [NSMutableArray array];
for (id itemfeed in jsonResult){
[names addObject:[NSString stringWithFormat:#"%#", itemfeed[#"ut"]]];
[bsLink addObject:[NSString stringWithFormat:#"%#", itemfeed[#"uu"]]];
[bLinks addObject:[NSString stringWithFormat:#"%#", itemfeed[#"upa"]]];
[daThor addObject:[NSString stringWithFormat:#"%#", itemfeed[#"pda"]]];
[ancTxt addObject:[NSString stringWithFormat:#"%#", itemfeed[#"lt"]]];
[folLowd addObject:[NSString stringWithFormat:#"%#", itemfeed[#"lf"]]];
self.links = names;
self.tNames = bLinks;
self.dThor = daThor;
self.theLinker = bsLink;
self.anText = ancTxt;
self.noDo = folLowd;
}
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[operation start];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
static NSString *Cellidentifier = #"DataTableCellId";
LICustomCell *cell = (LICustomCell *) [tableView dequeueReusableCellWithIdentifier:Cellidentifier];
if (cell == nil) {
cell = [[LICustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Cellidentifier];
NSArray *nib = [[NSBundle mainBundle]loadNibNamed:#"LiCellView" owner:self options:nil];
cell = nib[0];
NSString *sLink = self.links[indexPath.row];
NSString *aLink = self.tNames[indexPath.row];
NSString *aDa = self.dThor[indexPath.row];
NSString *theInk = self.theLinker[indexPath.row];
NSString *thAnk = self.anText[indexPath.row];
NSString *fLink = self.noDo[indexPath.row];
cell.ageLable.text = theInk;
}
return cell;
}
Looks like the data for your tableView is in 6 different arrays.
NSString *sLink = self.links[indexPath.row];
NSString *aLink = self.tNames[indexPath.row];
NSString *aDa = self.dThor[indexPath.row];
NSString *theInk = self.theLinker[indexPath.row];
NSString *thAnk = self.anText[indexPath.row];
NSString *fLink = self.noDo[indexPath.row];
Shouldn't you be sorting all of them? As your code stands now it's not clear how arrayToSort is connected to the data model of your tableView. You have NSArray *arrayToSort = data;, but it's not clear where data is initialized or where it's set (seems like you would want to set that in your JSON competition block). You also need to call [self.tableView reloadData]; at the end of MySegmentControlAction.
You can create a subclass of NSObject that has 6 NSString properties call it something like MyObject (but more descriptive). Then do something like:
for (id itemfeed in jsonResult){
MyObject *object = [[MyObject alloc]init];
object.sLink = [NSString stringWithFormat:#"%#", itemfeed[#"ut"]];
object.aLink = [NSString stringWithFormat:#"%#", itemfeed[#"uu"]];
...
[self.data addObject:object];
}
In the JSON competition block.
You then change cellForRowAtIndexPath to include something like
MyObject *object = [self.data objectAtIndex:indexPath.row]
cell.ageLable.text = object.theInk;
If you go this route you also need to update:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"pda" ascending:NO];
specifically #"pda" to whatever you name the property in your NSObject subclass. #"dThor" if you follow the naming I used.

Tableview is not showing cells in the time i posted

I have created a app that fetches information from a blog and shows it in the app. After i fetch the data it is supposed to be shown on the table view. It shows the things that i have posted but the things are in alphabetical order rather than the time i posted the thing.
Here is the code
#implementation EventsTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.firstLettersArray = [NSMutableArray array];
self.eventsDictionary = [NSMutableDictionary dictionary];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self searchForEvents];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[self searchForEvents];
}
- (void)searchForEvents
{
[self.searchBar resignFirstResponder];
NSString *eventsSearchUrlString = [NSString stringWithFormat:#"https://www.googleapis.com/blogger/v3/blogs/1562818803553764290/posts?key=AIzaSyBTOxz-vPHgzIkw9k88hDKd99ILTaXTt0Y"];
NSURL *eventsSearchUrl = [NSURL URLWithString:eventsSearchUrlString];
NSURLRequest *eventsSearchUrlRequest = [NSURLRequest requestWithURL:eventsSearchUrl];
NSURLSession *sharedUrlSession = [NSURLSession sharedSession];
NSURLSessionDataTask *searchEventsTask =
[sharedUrlSession dataTaskWithRequest:eventsSearchUrlRequest completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error)
{
dispatch_async(dispatch_get_main_queue(),
^{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if(error)
{
UIAlertView *searchAlertView = [[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[searchAlertView show];
}
else
{
NSString *resultString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Search results: %#", resultString);
NSError *jsonParseError = nil;
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParseError];
if(jsonParseError)
{
UIAlertView *jsonParseErrorAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:jsonParseError.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[jsonParseErrorAlert show];
}
else
{
for(NSString *key in jsonDictionary.keyEnumerator)
{
NSLog(#"First level key: %#", key);
}
[self.firstLettersArray removeAllObjects];
[self.eventsDictionary removeAllObjects];
NSArray *searchResultsArray = [jsonDictionary objectForKey:#"items"];
//NSLog(#"test%#",searchResultsArray);
for(NSDictionary *eventsInfoDictionary in searchResultsArray)
{
Events *event = [[Events alloc] init];
event.eventName = [eventsInfoDictionary objectForKey:#"title"];
event.eventDescription =[eventsInfoDictionary objectForKey:#"content"];
NSLog(#"Event Name : %#",event.eventName);
NSLog(#"Event Description : %#",event.eventDescription);
NSString *eventsFirstLetter = [event.eventName substringToIndex:1];
NSMutableArray *eventsWithFirstLetter = [self.eventsDictionary objectForKey:eventsFirstLetter];
if(!eventsWithFirstLetter)
{
eventsWithFirstLetter = [NSMutableArray array];
[self.firstLettersArray addObject:eventsFirstLetter];
}
[eventsWithFirstLetter addObject:event];
[self.eventsDictionary setObject:eventsWithFirstLetter forKey:eventsFirstLetter];
if ([event.eventDescription containsString:#"<br />"]) {
NSString* eventDescrip = event.eventDescription;
NSString* stringWithoutHTMLtags = [eventDescrip stringByReplacingOccurrencesOfString:#"<br />" withString:#""];
event.eventDescription = stringWithoutHTMLtags;
}
NSLog(#"Event Name : %#",event.eventName);
NSLog(#"Event Description : %#",event.eventDescription);
}
[self.firstLettersArray sortUsingSelector:#selector(compare:)];
[self.tableView reloadData];
}
}
});
}];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[searchEventsTask resume];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.firstLettersArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *firstLetter = [self.firstLettersArray objectAtIndex:section];
NSArray *eventsWithFirstLetter = [self.eventsDictionary objectForKey:firstLetter];
return eventsWithFirstLetter.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"eventTitleCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSString *firstLetter = [self.firstLettersArray objectAtIndex:indexPath.section];
NSArray *eventsWithFirstLetter = [self.eventsDictionary objectForKey:firstLetter];
Events *event = [eventsWithFirstLetter objectAtIndex:indexPath.row];
cell.textLabel.text = event.eventName;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
/*
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = cell.textLabel.text;
NSLog(#"Row selected %#",cellText);*/
NSString *firstLetter = [self.firstLettersArray objectAtIndex:indexPath.section];
NSArray *eventsWithFirstLetter = [self.eventsDictionary objectForKey:firstLetter];
Events *event = [eventsWithFirstLetter objectAtIndex:indexPath.row];
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:#"Main" bundle: nil];
DescriptionViewController *descriptionViewController = (DescriptionViewController*)[mainStoryboard instantiateViewControllerWithIdentifier: #"descriptionController"];
descriptionViewController.eventNameDesc = event.eventDescription;
descriptionViewController.navigationItem.title = event.eventName;
[self.navigationController pushViewController:descriptionViewController animated:YES];
}
#end
You are trying to sort firstLettersArray which contain Events objects by using standard sort: function which doesn't know how to work with your custom objects.
You can use sortedArrayUsingComparator: function like this:
[firstLettersArray sortedArrayUsingComparator:^NSComparisonResult(Events *obj1, Events *obj2) {
// return object comparison result here
}];
Edit: Also you need to have NSDate property in Events class and feel it with event created time. I believe event created time should be contained in eventsInfoDictionary. Eventually you will be able to compare obj1 and obj2 using NSDate property.
i think this line not working
[self.firstLettersArray sortUsingSelector:#selector(compare:)];
use this line of code may help you....
sortedArray = [anArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];

Custom UICollectionViewCell not loading

I'm using a storyboard and my custom UICollectionViewCell is not appearing. I played around with it for a few hours and have googled a ton of different solutions but none worked. Just to clarify, the data exists, and the UICollectionView is appearing, but the cell is not. Here is my code. Any suggestions would be appreciated!
- (NSInteger)collectionView:(UICollectionView *)mutualFriendsView numberOfItemsInSection:(NSInteger)section {
return [self.resultsDictionary count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)mutualFriendsView
cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = #"PCRRequesterMutualFriendsCollectionViewCell";
PCRRequesterMutualFriendsCollectionViewCell *cell = [self.mutualFriendsView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
NSArray *idArray = [self.resultsDictionary objectForKey:#"id"];
NSArray *nameArray = [self.resultsDictionary objectForKey:#"name"];
cell.profileName.text = [nameArray objectAtIndex:indexPath.row];
cell.backgroundColor = [UIColor redColor];
return cell;
}
- (void)collectionView:(UICollectionView *)mutualFriendsView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"cell #%d was selected", indexPath.row);
}
- (BOOL)shouldAutorotate {
[mutualFriendsView.collectionViewLayout invalidateLayout];
BOOL retVal = YES;
return retVal;
}
EDIT Here is my viewDidLoad
self.mutualFriendsView.dataSource = self;
self.mutualFriendsView.delegate = self;
self.mutualFriendsView.pagingEnabled = YES;
// [self.mutualFriendsView registerClass:[PCRMutualFriendsCollectionViewCell class] forCellWithReuseIdentifier:#"PCRMutualFriendsCollectionViewCell"];
Edit I think I figured out the problem. I don't think the dictionary is being populated after the completion block finishes. Any suggestions for saving the value of the dictionary from the block to be used outside of it?
__block NSMutableDictionary *mutualFriends = nil;
__block NSNumber *total;
NSString *u = [NSString stringWithFormat:#"%#",self.details[#"Requester"][#"profile"][#"facebookId"]];
/* make the API call */
[FBRequestConnection startWithGraphPath:(#"/%#", u)
parameters:params
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
/* handle the result */
if (!error){
NSLog(#"RESULT OF FB %#", result);
if (result == nil){
NSLog(#"No shared friends");
} else {
total = result[#"context"][#"mutual_friends"][#"summary"][#"total_count"];
NSLog(#"TOTAL FRIENDS %#", total);
for(int i=0;i<[result[#"context"][#"mutual_friends"][#"data"] count];i++)
{
mutualFriends = result[#"context"][#"mutual_friends"][#"data"][i];
NSLog(#"FRIENDDATA %#", mutualFriends);
}
}
} else {
NSLog(#"ERROR %#", error);
}
}];
self.resultsDictionary = mutualFriends;
self.number = total;
NSLog(#"NUMBER %#", self.number);
NSLog(#"RESULTS DICTIONARY %#", self.resultsDictionary);
NSString *friends = [NSString stringWithFormat:#"You have %# friends in common including:", self.number];
After this code:
for(int i=0;i<[result[#"context"][#"mutual_friends"][#"data"] count];i++)
{
mutualFriends = result[#"context"][#"mutual_friends"][#"data"][i];
NSLog(#"FRIENDDATA %#", mutualFriends);
}
// add
self.resultsDictionary = mutualFriends;
mutualFriendsView.reloadData();
All within that completion block. So when FB finally does return and you've accumulated all the mutualFriends, then you tell the collectionView to reload.

NSPredicate search through NSMutableArray

I have a view controller that retrieves address information from my web service, stores it in a mutable array and then displays each address in a table view. I have a search bar on the same view controller that i'd like to search through each of the addresses and display the results. I have this working with a test NSArray, however I'm not sure what I need to do to the filterContentForSearchText function to get it to search through an NSMutableArray. Any help appreciated.
Object Class
// Branches.h
#interface Branches : NSObject
#property (nonatomic, retain) NSString *BranchAddress;
#end
View Controller Class
// ViewController.h
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate>
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#end
.
// ViewController.m
#import "AFHTTPRequestOperationManager.h"
#import "ViewController.h"
#import "Branches.h"
#interface ViewController () {
NSMutableArray *array;
}
#property (strong, nonatomic) NSArray *searchResults;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Initialize myArray
array = [[NSMutableArray alloc] init];
// Set POST parameters
NSDictionary *parameters = #{#"key" : #"value"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"webservice_address" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
// Check to see if responseObject contains data
if (responseObject != nil) {
// Loop through JSON
for (NSDictionary *dictionary in responseObject) {
// Initialize object
Branches *branches = [[Branches alloc] init];
branches.branchAddress = [dictionary objectForKey:#"Object"];
// Add object to myArray
[array addObject:branches];
[self.tableView reloadData];
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
#pragma Table View Methods
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [self.searchResults count];
} else {
return [array count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [[array objectAtIndex:indexPath.row] BranchAddress];
}
return cell;
}
#pragma Search Methods
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSArray *masterArray = array;
NSArray *searchResults = [masterArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(Branches *evaluatedObject, NSDictionary *bindings) {
//NSLog(#"%#", evaluatedObject.BranchAddress);
return ([evaluatedObject.BranchAddress rangeOfString: searchText options:NSCaseInsensitiveSearch].location != NSNotFound);
}]];
NSLog(#" %i", searchResults.count);
//[searchResults removeAllObjects];
//[searchResults addObjectsFromArray:searchResults];
//reload after this
NSLog(#"%#", [searchResults objectAtIndex:0]);
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
#end
u can try this
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSArray *masterArray = self.array;
NSArray *resultsArray = [masterArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(Branches *evaluatedObject, NSDictionary *bindings) {
return ([evaluatedObject.BranchAddress rangeOfString: searchText options:NSCaseInsensitiveSearch].location != NSNotFound);
}]];
//edited
[self.searchResults removeAllObjects]; //self.searchResults should be mutable array
[self.searchResults addObjectsFromArray:resultsArray];//put the new values to searchResults
//after this self.searchResults contains objects of filtered Branches u can get the values for example
NSLog(#"%#", [[self.searchResults objectAtIndex:0] BranchAddress]);//self.searchResults contains objects of Branches not the string itself
//reload after this
}

Resources