Xcode how to display array inside array in tableview - ios

In Xcode5 I have application of recipes.
screen1 is list of recipes in a tableview. The recipe are objects in an array at MVC model. at Screen1 when clicking on a row you move to screen2 to see a specific recipe Details. One of them is Ingredients which I try to display as array (inside array) in UITextView (divided by \n).
I run the app - screen1 is displayed, but when clicking a row the app crashes at: signal SIGABRT.
Can you please advise what is best way to display array of ingredients in the textview?
Thanks in advance.
This is code at DetailsVC.m (screen2):
-(void)viewWillAppear:(BOOL)animated {
self.detailName.text = self.presentedRecipe.title;
self.detailImage.image = [UIImage imageNamed:self.presentedRecipe.imageName];
NSMutableString *ingredientText = [NSMutableString string];
for (NSString* ingredient in myRecipeDM.ingredients) {
[ingredientText appendFormat:#"%#\n", ingredient];
}
self.ingTV.text = (NSString*) self.presentedRecipe.ingredients;
}

Try
NSString *final=[[NSString alloc] init];
for (NSString* ingredient in myRecipeDM.ingredients)
{
if[ingredientText isEqualToString:""]
{
ingredientText=ingredient;
}
else
{
ingredientText=final;
ingredientText=[final stringByAppendingFormat:#"%#\n", ingredient];
}
}

You can use:
NSString *ingredientstring = #"";
for (NSString* ingredient in myRecipeDM.ingredients)
{
ingredientstring = [NSString stringWithFormat:#"%#\n%#", ingredientstring, ingredient];
}
_ingTV.text = ingredientstring;

Related

I need to have a mutable Array that has 8 interpolated strings in IOS

I'm new to IOS and I'm not sure if I'm on the right track. What I need to know is if I'm on the right track and if I'm off it a hint on what to fix so I can get back on track. The mutable Array should read an array of speakers and say "Hello, my name is <speakerArray>" it should do that 8 times with a different name each time. This is what I Have:
- (NSArray*)badgesForSpeakers:(NSArray*)speakers {
for(speakers i = 0; i => 7; i++)
{
NSString *greetings =#"Hello, my name is .";
NSMutableArray *badges = [speakers arrayByAddingObjectsFromArray:greetings];
}
return badges;
}
Let's take this one step at a time. First of all, your operator in the loop is wrong; you mean to execute while i is less than or equal to 7. Thus, change => to <=. However, it's more stylish to say i < 8. And finally, it's most stylish of all to use what's called "Fast Enumeration", which allows you to loop without an index at all. In fact, it will work no matter how many items are in your speakers array! That takes us here:
- (NSArray*)badgesForSpeakers:(NSArray*)speakers {
for (NSString* speaker in speakers)
{
NSString *greetings =#"Hello, my name is .";
NSMutableArray *badges = [speakers arrayByAddingObjectsFromArray:greetings];
}
return badges;
}
Next, greetings isn't an array! It's a string. That's why calling -arrayByAddingObjectsFromArray: doesn't make any sense, and why the compiler isn't going to like it. Let's make its name singular, greeting, to reflect this fact. Strategy: Your goal here is to create an empty array, then construct items one by one and add them to that array. That takes us to:
- (NSArray*)badgesForSpeakers:(NSArray*)speakers {
NSMutableArray *badges = [NSMutableArray array]; //Here we make an empty array
for (NSString* speaker in speakers)
{
NSString *greeting =#"Hello, my name is .";
[badges addObject:greeting]; //Here we add one item to it each time 'round the loop
}
return badges;
}
Last, your string has no interpolation right now! It reads literally "Hello, my name is ." We do string interpolation using the -stringWithFormat: method.
Finished Product:
- (NSArray*)badgesForSpeakers:(NSArray*)speakers {
NSMutableArray *badges = [NSMutableArray array];
for (NSString* speaker in speakers)
{
NSString *greeting = [NSString stringWithFormat:#"Hello, my name is %#.",speaker];
[badges addObject:greeting];
}
return badges;
}
That should get you started with fast enumeration and string interpolation. Remember to compile your code often and try to understand the compiler errors--it would have helped you with some of these issues.
Maybe you mean this
- (NSMutableArray *)badgesForSpeakers:(NSArray *)speakers {
NSMutableArray *badges = [[NSMutableArray alloc] init];
for (NSString *speaker in speakers) {
[badges addObject:[NSString stringWithFormat:#"Hello, my name is %#", speaker]];
}
return badges;
}
plz use this code
- (NSArray*)badgesForSpeakers:(NSArray*)speakers {
NSMutableArray *badges = [NSMutableArray alloc];
for(int i = 0; i < speakers.count; i++)
{
NSString *greetings =[NSString stringWithFormat:#"Hello, my name is .%#",[speakers objectAtIndex:i]];
badges = [speakers addObject:greetings];
}
return [badges copy];
}

how to add the button clicks and count in a dictionary

I have a method called addbuttonClicktocounter. When the function is called it should add the button name as key and number of clicks as count. I made this in my static library. When the user called these method again and again it should capture all the button names and number of clicks in one dictionary. If same button clicks again and again means the button name should remain same and the click count oly get increased. Here is my code what my tried upto my level:
NSMutableDictionary *BtnclicDict;
-(void) addButtonClickToCounter : (NSString*)button_Name button_click :(int)but_Click{
if([[BtnclicDict allKeys] containsObject:button_Name]){
int saveClick = [[BtnclicDict valueForKey:button_Name] integerValue];
but_Click = saveClick + but_Click;
NSNumber *click = [NSNumber numberWithInt:but_Click];
NSString *clickString = [click stringValue];
[BtnclicDict setObject:clickString forKey:button_Name];
NSLog(#"same button...,%#",click);
NSLog(#"same key dict...,%#",BtnclicDict);
} else {
NSString *but_Name = [NSString stringWithString:button_Name];
// NSLog(#"%#",but_Name);
NSNumber *click = [NSNumber numberWithInt:but_Click];
// NSLog(#"%#",click);
NSString *clickString = [click stringValue];
// BtnclicDict = [NSMutableDictionary dictionaryWithObject:but_Name forKey:click];
// BtnclicDict = [[NSMutableDictionary alloc]init];
[BtnclicDict setObject:clickString forKey:but_Name];
NSLog(#"working,%#",BtnclicDict);
// NSLog(#"%# Button Values...",BtnclicDict);
}
}
If you call this method from another class again and again it should collect all the details and make it into one dictionary.
You can try this.
-(void) addButtonClickToCounter : (NSString*)button_Name button_click :(int)but_Click{
if ([BtnclicDict valueForKey:buttonName])
but_Click += [[BtnclicDict valueForKey:button_Name] integerValue];
[BtnclicDict setValue:but_Click forKey:button_Name];
}

How to filter search within a set of letters in search bar so that each letter typed will reduce the results in objective -c

i have implemented a search bar that searching trough an array of countries(presented in a picker view), the problem is that the user need to type the full country name that it will find it and i want him to be able to type even one letter and it will show the first country that starts with that letter and if types another than it sorts even further etc etc.
Anyone have any ideas??
for(int x = 0; x < countryTable.count; x++){
NSString *countryName = [[countryTable objectAtIndex:x]objectForKey:#"name"];
if([searchedStr isEqualToString:countryName.lowercaseString]){
[self.picker selectRow:i inComponent:0 animated:YES];
flag.image = [UIImage imageNamed:[[countryTable objectAtIndex:i]objectForKey:#"flag"]];
}
}
There's a method on NSArray called filteredArrayUsingPredicate: and a method on NSString called hasPrefix:. Together they do what you need...
NSString *userInput = //... user input as lowercase string. don't call this countryName, its confusing
NSPredicate *p = [NSPredicate predicateWithBlock:^BOOL(id element, NSDictionary *bind) {
NSString countryName = [[element objectForKey:#"name"] lowercaseString];
return [countryName hasPrefix:userInput];
}];
NSArray *filteredCountries = [countryTable filteredArrayUsingPredicate:p];
If you're on iOS 8 or OS X Yosemite, you can do:
NSString *country = countryName.lowercaseString; //"england"
NSString *needle = #"engl";
if (![country containsString:needle]) {
NSLog(#"Country string does not contain part (or whole) of searched country");
} else {
NSLog(#"Found the country!");
}
Else, if on versions below iOS 8:
NSString *country = countryName.lowercaseString; //"england"
NSString *needle = #"engl";
if ([country rangeOfString:needle].location == NSNotFound) {
NSLog(#"Country string does not contain part (or whole) of searched country");
} else {
NSLog(#"Found the country!");
}
Lastly, just iterate through all possible countries and apply this to them all. There might exist more robust solutions out there (like danh's solution with some smaller modifications), but this is by far the easiest to start with.

select indexOfObject from NSArray in Xcode by comparing string

Hi I have NSarray values in Xcode. I need to get array indexOfObject by comparing string values.
my array values are
(
{
firstName = lord;
lastname = krishna;
},
{
firstName = priya;
lastname = amirtha;
}
)
If I type first name in textfield and click button means last name want to display in another textfield.
thank you.
To answer the title of your question:
NSString *compareString = #"something";
NSMutableArray *indexesOfMatches = [[NSMutableArray alloc]init];
for (NSString *string in theArray) {
if ([string isEqualToString:compareString]) {
NSNumber *index = [[NSNumber numberWithInterger:[theArray indexOfObject:string]];
[indexOfMatches addObject:index];
}
}
//indexOfMatches will now contain NSNumber objects that represent the indexes of each of the matching string objects in the array
I think that using an NSDictionary would be better for you though. Then you can simply keep the first and last names as Key Value pairs.
NSDictionary *names = #{#"lord" : #"krishna", #"priya" : #"amirtha" };
Then you can just do value for key when you get the first name:
NSString *firstName = #"lord";
NSString *lastName = [names valueForKey:firstName];
Store firstNameArray and lastNameArray a mutable array NSMutableArray.
Using Fast Enumeration. Suppose array is the array you are provided with
for (NSDictionary *item in array) {
[firstNameArray addObject:[item objectForKey:#"firstName"]];
[lastNameArray addObject:[item objectForKey:#"lastName"]];
}
After entering the data in firstNameTextField click the button
Button action method implementation
-(IBAction)btnClicked:(id)sender {
NSInteger index = [firstName indexOfObject:[firstNameTextField text]];
[lastNameTextField setText:[lastName objectAtIndex:index]];
}

How can I access one value among some values

{
"id"=12
"genres_en" = "thriller,movies,action";
}
{
"id"=13
"genres_en" = "thriller,horror";
}
Hi everyone ,
I have one json like this..I mean i have one content and all movie has their genre ..And i need to do one categorization ..For example I need to check which genre of movie is horror..Or which one is thriller..I m getting all value like this:
--> "horror,movies"
But how can i do the controllation to check whether the genre of this movie includes horror or not..??what is your suggesstion?
Thank you
You could use componentsSeparatedByString
NSDictionary *dic = PARSE The JSON;
NSString *values = [dic objectForKey:"genres_en"];
NSString *firstValue = [[values componentsSeparatedByString:","] objectAtIndex:0];
I don't have Xcode nearby, so the following code may contain an error(or two :) ).
Try it like that:
NSDictionary *yourDict = //your parsed json
NSString *genres = [yourDict objectForKey:#"genres_en"];
if ([genres rangeOfString:#"horror"].location != NSNotFound) {
return YES;
} else {
return NO;
}
Hope it helps
for(int j=0;j< GenresArray.count; j++)
{
NSString *value=[[genre componentsSeparatedByString: #","]objectAtIndex:j];
if([value isEqualToString:#"movies"])
{
[genreMovies addObject:value];
}
}
Thank you for your help guys ..Now i have my result:)
You can try to check if the string contains the substring you want . Like this:
NSString *typesString = [dic objectForKey:"genres_en"];
NSRange range = [typesString rangeOfString:#"horror"];
if(range.location != NSNotFound)
{
//it contains the substring "horror"
}
Or , the better way would be to get the array of types.
NSArray *types = [[typesString componentsSeparatedByString:","];
Now you can store this array for each entry and whenever you want to check if it belongs to a certain gender , just loop through the types array ( of each entry ) and compare the strings.
Hope this helps.
Cheers!

Resources