Set a UITextField from an NSArray - uitextfield

I have tried many variations with no luck. I can NSLog the array and I get this:
2011-07-17 00:54:54.886 Widgets[13444:207] <Widget: 0x5e2aad0> (entity: Widget; id: 0x5e0d8e0 <x-coredata://E64A0BCE-2344-4EE1-89CC-164ACD8995D6/Recipe/p115> ; data: {
success = 1;
coconutscarried = nil;
name = "African Swallow";
uidnumber = "105 ";
})
How can I simple set a text field?
Pardon the mess but this is an assortment of code I have tried (messy). The array and text field have been set up in .h/m and bound in IB
- (void)viewDidLoad {
[super viewDidLoad];
//NSLog(#"%#",[[swallowArray name] text]); // doesnt work
//NSLog(#"The string at index is %#.", [self.swallowArray objectAtIndex:0]);//nope...
for (int i = 0; i < [swallowArray count]; i++) {
//nameTextField.text = [[swallowArray objectAtIndex:i] uidnumber];
//NSLog(#"%#",swallowArray.name);
//}
//nameTextField.text = [[swallowArray objectAtIndex:0] uidnumber];
//NSString* strRate = [[swallowArray object] uidnumber];
nameTextField.text = [nameTextField.text stringByAppendingString:[NSString localizedStringWithFormat:#", %#", [[swallowArray objectAtIndex:i] name]]];
}
and many more. This has got to be dead simple, but I am kind of a noob.
thanks!
bo

after 5 hours of searching, I post here, and find the answer in literally five minutes!
NSString *nameFromArray = [NSString stringWithFormat:#"%#", [eventArray valueForKey:#"name"]];
NSLog(#"%#", nameFromArray);
Hope this helps someone else!

Related

Xcode Search Bar - Can't search through NSObjects containing NSStrings

So I'm adding a search bar to my custom tableview with custom cells, and it's giving an error.
-[Game rangeOfString:options:]: unrecognized selector sent to instance 0x170244e60
2016-10-15 15:41:49.557956 CustomCellApp[25930:7889617]
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Game rangeOfString:options:]: unrecognized selector sent to instance 0x170244e60
I'm populating my tableview by an array containing NSObjects which contain strings (gamesArray)and those strings I'm getting it from a JSON array (jsonArray), all from a php file connecting to a MYSQL server which have all the strings.
Here is the code for the search bar:
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if (searchText.length == 0) {
isFiltered = NO;
} else {
isFiltered = YES;
filteredGamesArray = [[NSMutableArray alloc] init];
// ----- Problem Method ----- //
for (NSString *str in gamesArray) {
// ----- Crashes Here ----- //
NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (stringRange.location != NSNotFound) {
[filteredGamesArray addObject:str];
}
}
// ------------------------------------ //
}
[myTableView reloadData];
}
Here is the code for the tableView:
// Configuring the cell
Game * gameObject;
// Showing either Normal List or Filtered List
if (!isFiltered) {
gameObject = [gamesArray objectAtIndex:indexPath.row];
}
else {
gameObject = [filteredGamesArray objectAtIndex:indexPath.row];
}
Here is the code from server
It adds the strings from the server to a jsonarray which is then added to an NSObject to an array called gamesArray
NSString * gID = [[jsonArray objectAtIndex:i] objectForKey:#"id"];
NSString * gName = [[jsonArray objectAtIndex:i] objectForKey:#"gameName"];
NSString * gLabel1 = [[jsonArray objectAtIndex:i] objectForKey:#"gameLabel1"];
NSString * gLabel2 = [[jsonArray objectAtIndex:i] objectForKey:#"gameLabel2"];
NSString * gLabel3 = [[jsonArray objectAtIndex:i] objectForKey:#"gameLabel3"];
Any help would be greatly appreciated!
How can I fix this? Any ideas? Thank you
I think the problem is that when searching, the program is seeing that it has an array to search through, gamesArray, but when going inside it has 5 NSObjects, each containing strings, so it's not working because it doesn't know what to do.
As a solution, how can I make it that the search bar searches through the gamesArray, directly at 1 NSObject, the gameName , reading all the strings in that NSObject which is called gName
For example, this piece of code targets a specific NSObject inside the gamesArray
[[gamesArray objectAtIndex:indexPath.row] valueForKey:#"gameName"];
My first guess is: objects in games array are not strings, they are Game objects.
for (Game *game in gamesArray) {
NSString *str = game.fieldOfInterest;
// ----- Crashes Here ----- //
NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (stringRange.location != NSNotFound) {
[filteredGamesArray addObject:game];
}
}
This should address the issue of your crash. If the search behavior is not correct, please ask a new question related to your new issue. As a best guess, I would suggest you inspect your table delegate methods for how they behave when filtered is true.

A label in a UIViewController, which refreshes every new view, with a new text

Every time you come to this view it should be always be random text.
I was searching for the script but I founded nothing!
Screenshot of the App: http://copticmovies.net/iphone/iphone5-video-logo.png
Thank you guys!
Presuming you have a UILabel in your view controller called 'myLabel', a quick and not-very elegant way to do it is:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
//quick and dirty random string generation
NSString *alphabet = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZY0123456789";
NSMutableString *s = [NSMutableString stringWithCapacity:20];
for (NSUInteger i = 0U; i < 20; i++) {
u_int32_t r = arc4random() % [alphabet length];
unichar c = [alphabet characterAtIndex:r];
[s appendFormat:#"%C", c];
}
self.myLabel.text = s;
}
Add an outlet to the label (eg rdmtext).
In your Viewcontroller edit the method:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.rdmtext.text = #"Your random text from any source";
}
For further details you should add what kind of random text you want to add. Where is it stored?

How to increment a 'score' during fast enumeration

I have the following code which I would like to use to check user answers and output a score (out of 5). I use a plist with the answers in and check the textField.text against it. What I'm struggling with is: how to get an output score as a total using this method?
- (IBAction)checkAnswers:(UITextField *)textField
{
NSString *path2 = [[NSBundle mainBundle] pathForResource:#"7A Cells Microscopes 3" ofType:#"plist"];
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:path2];
NSString *tester = [NSString stringWithFormat:#"%i", textField.tag];
// NSDictionary *secondDict = [dictionary valueForKey:tester];
// NSString *answer = [secondDict valueForKey:#"Answer"];
// if ([textField.text isEqualToString:[[dictionary valueForKey:tester] valueForKey:#"Answer"]]) {
// NSLog(#"YAY");
// }
NSArray *allTextFields = [[NSArray alloc] initWithObjects:eyepiece, objectiveLens, focussingKnobs, stage, mirror, nil];
for (textField in allTextFields) {
int x = 0;
if ([textField.text isEqualToString:[[dictionary valueForKey:tester] valueForKey:#"Answer"]]) {
x++;
NSLog(#"%i", x);
}
}
Any help would be much appreciated!
Many thanks.
Assuming the rest of your code is good, just move int x = 0; outside the for loop. The way you have it coded x is reset to 0 on every loop... so it never counts.

Adding multiple strings to a string

How do I add multiple strings to a string ?
Whats the easiest way to do that ?
If I don't want to create a new line of code every time I add something to a string, I'd like to do something like that :
NSString *recipeTitle = [#"<h5>Recipe name: " stringByAppendingFormat:recipe.name, #"</h5>"];
NSLog(#"%#", recipeTitle);
// This shows: <h5>Recipe name: myrecipe
// Where's the </h5> closing that header ? It will only show up with the next line of code
recipeTitle = [recipeTitle stringByAppendingFormat:#"</h5>"];
//my problem is that will result in more than 1k lines of programming
Do I have to necessarily add a new line appending the appended every time ?
Is there a faster/more productive way to do that ?
I'm trying to compose the email body with my tableview in it and that will result in a huge set of programming lines. Isthere anybody that could give me any hint or anything better than composing a huuuge string just so i can populate my email body with a table containing my tableview data ?
Any help to make this more productive is appreciated. Thanks !
Carlos Farini.
// After working on it a bit i got:
-(IBAction)sendmail{
MFMailComposeViewController *composer = [[MFMailComposeViewController alloc] init];
[composer setMailComposeDelegate:self];
NSString *recipeTitle = #"<h5>Recipe name: ";
recipeTitle = [recipeTitle stringByAppendingFormat:recipe.name];
recipeTitle = [recipeTitle stringByAppendingFormat:#"</h5>"];
NSString *ingredientAmount = #"";
NSString *ingredientAisle = #"";
NSString *ingredientTitle = #"";
NSString *tableFirstLine = #"<table width='90%' border='1'><tr><td>Ingredient</td><td>Amount</td><td>Aisle</td></tr>";
NSString *increments = #"";
int i=0;
for (i=0; i < [ingredients count]; i++) {
Ingredient *ingredient = [ingredients objectAtIndex:i];
ingredientTitle = ingredient.name;
ingredientAmount = ingredient.amount;
ingredientAisle = ingredient.aisle;
increments = [increments stringByAppendingFormat:recipeTitle];
increments = [tableFirstLine stringByAppendingFormat:#"<tr><td>"];
increments = [increments stringByAppendingFormat:ingredientTitle];
increments = [increments stringByAppendingFormat:#"</td><td>"];
increments = [increments stringByAppendingFormat:ingredientAmount];
increments = [increments stringByAppendingFormat:#"</td><td>"];
increments = [increments stringByAppendingFormat:ingredientAisle];
increments = [increments stringByAppendingFormat:#"</td></tr>"];
if (i == ([ingredients count]-1)) {
//IF THIS IS THE LAST INGREDIENT, CLOSE THE TABLE
increments = [increments stringByAppendingFormat:#"</table>"];
}
}
NSLog(#"CODE:: %#", increments);
if ([MFMailComposeViewController canSendMail]) {
[composer setToRecipients:[NSArray arrayWithObjects:#"123#abc.com", nil]];
[composer setSubject:#"subject here"];
[composer setMessageBody:increments isHTML:YES];
[composer setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentModalViewController:composer animated:YES];
[composer release];
}else {
[composer release];
}
}
But then again, it's showing just one row in the table. What am I doing wrong here ?
How about something like this:
NSString *recipeTitle = [NSString stringWithFormat:#"<h5>Recipe name: %# </h5>", recipe.name];

returning an NSObject - bad exec

I've been struggling with a problem that I hope someone can help me with.
I have Class called 'GameObjectDefinitionTable', where I set all my object properties, which is in another class called 'Product'. In my 'HelloWorldScene' I allocate 'GameObjectDefinitionTable' which in turn creates several 'Product's. Like this:
HelloWorldScene -> GameObjectDefinitionTable -> Product
I then want to return a 'Product' to 'HelloWorldScene. But here is where I get problems. Some code:
HelloWorldScene:
GameObjectDefinitionTable *god = [[GameObjectDefinitionTable alloc]init];
Product* currentProduct = [god getProductWithNum:0];
NSLog(#"currenProduct (name): %#",currentProduct.name); //Crash
GameObjectDefinitionTable:
-(void) createProducts {
Product *product;
for (int i=0; i<[allProductsWithDefinitions count];i++ ) {
product = [[Product alloc]init];
product.name = [[allProductsWithDefinitions objectAtIndex:i] objectAtIndex:0];
product.density = [[[allProductsWithDefinitions objectAtIndex:i] objectAtIndex:1] floatValue];
product.scoreValue = [[[allProductsWithDefinitions objectAtIndex:i] objectAtIndex:2] intValue];
product.fileName = [[allProductsWithDefinitions objectAtIndex:i] objectAtIndex:3];
[products addObject:product];
[product release];
}
[allProductsWithDefinitions release];
}
-(Product *) getProductWithNum:(int)tNum {
Product *tempProduct;
tempProduct = [products objectAtIndex:tNum];
return tempProduct;
[tempProduct release];
}
The arrays and all in 'GameObjectDefinitionTable' is working fine if I log in that class.
Would be really grateful for an answer :)
Is it the case you need something like:
- (Product *)getProductWithNum:(int)tNum
{
Product *tempProduct = [[products objectAtIndex:tNum] retain];
return [tempProduct autorelease];
}
Product *tempProduct;
tempProduct = [products objectAtIndex:tNum];
return tempProduct;
[tempProduct release];
Is that what you mean to have? You kind of have two big problems cancelling each other out here. The [tempProduct release]; line is unreachable. The second, if you were to actually execute [tempProduct release]; before the return, you would be releasing the memory, and then accessing the currentProduct.name property of what is essentially a dangling pointer. This illegal memory access could cause your Bad Exec.
Since you are not allocating, copying, or retaining tempProduct, you must NOT release it. Why not just a simple return [products objectAtIndex:tNum];?

Resources