Show elements of array in button text in Objective-C - ios

I'm saving the textfields data in SQLite when click the save button. Now I want to show that data in button text. I'm getting data from SQLite in an NSMutableArray, but when I set the titleLabel of button it does not appear there. How can I get the array data in button text. My code to get data from SQLite is this:
- (IBAction)btnShow:(id)sender {
NSString *show=[[NSString alloc]initWithFormat:#"select * from persondata where id='%#'",_txtID.text];
dboperation *db = [[dboperation alloc]init];
_arrmainData = [[NSMutableArray alloc]init];
_arrmainData=[db getalluser:show];
NSLog(#"Arr %#",_arrmainData);
for (NSDictionary * oneCustomer in _arrmainData){
[oneCustomer objectForKey:#"address"];
NSLog(#"ID: %# ",oneCustomer);
_btnShowData.titleLabel.text = [NSString stringWithFormat:#"%#",oneCustomer];
NSLog(#"XX %#",_btnShowData.titleLabel.text);
}
}

Set the title like this
[_btnShowData setTitle: [NSString stringWithFormat:#"%#", [oneCustomer objectForKey:#"address"]] forState:UIControlStateNormal];

Try to replace
_btnShowData.titleLabel.text = [NSString stringWithFormat:#"%#",oneCustomer];
with
[_btnShowData setTitle:[NSString stringWithFormat:#"%#",oneCustomer] forState:UIControlStateNormal];

Related

how to Display data get from JSON in View controller

I have idea how to display data in UITableViewController in cell by index.row but i don't have idea how to show data in viewController
for e.g.
when i use UITableViewController that time,
NSString *str = [NSString stringWithFormat:#"%#", [[self.data
objectAtIndex:indexPath.row ] valueForKey:#"profile_image"]]; // data
is my array
this code will get image from array and set it in particular cell with the help of index.row.
but when i am using UIViewController then how i should set data for particular view??
Please provide me your guidance for this issue that how can i set image form array to my ViewController as i set it in UITableViewController by objectAtIndex:indexPath.row .
Thanks
i asked the above question but i got answer myself after many research and defiantly with the help of my stackoverflow's intelligent friends.
so i like to post my answer.
my answer is if i take int value i and then i use it in my function then it look like below code..
[requestDynamic startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
// Insert your code here
NSLog(#"%#",result);
self.arrData = nil;
self.arrData = [[NSMutableArray alloc]init];
self.arrData = [result[#"data"] mutableCopy];
int i =0;
// NSString *strImage1 = [NSString stringWithFormat:#"%#",[[self.arrData objectAtIndex:i]valueForKey:#"picture"]];
NSString *strComment =[NSString stringWithFormat:#"%#", [[self.arrData objectAtIndex:i ]valueForKey:#"message"]];
NSString *strLike = [NSString stringWithFormat:#"%#", [[[[self.arrData objectAtIndex:i]valueForKey:#"likes"]valueForKey:#"summary"]valueForKey:#"total_count"]];
NSString *strCommentCount = [NSString stringWithFormat:#"%#", [[[[self.arrData objectAtIndex:i]valueForKey:#"comments"]valueForKey:#"summary"]valueForKey:#"total_count"]];
CustomSocialView *imageView1 = [[CustomSocialView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
[imageView1 setContentText:strComment like:strLike comment:strCommentCount];
may be this question and answer is silly for you all experienced people but it is very important for me and some others like me.
so i post answer as i got it.
Thank you

UIButton Title not updating all the time

I am programmatically changing the title of a UIButton to display count of items in a NSMutableArray.
Sometimes, the title does not update as I add items to the array. When I do the NSLog of what the title should be, it is correct but the button title does not update all the time.
Can anyone spot a problem with my code?
- (void) refreshAfterBlueToothScan
{
/*************************************Refresh Displayed Total********************/
//[_manualBCtemporaryCartArray26 removeAllObjects];
//_manualBCtemporaryCartArray26 = [[NSMutableArray alloc] init];
[localTempArray removeAllObjects];
if (!localTempArray)
{
localTempArray = [[NSMutableArray alloc] init];
}
// Get the DBAccess object;
DBAccess *dbAccess1 = [[DBAccess alloc] init];
// Get the products array from the database
//Get the latest NSMutableArray
localTempArray = [dbAccess1 getProductsFromTmpSales];
// Close the database because we are finished with it
[dbAccess1 closeDatabase];
//Count How many products in array
int iNumberofArrayProducts;
iNumberofArrayProducts = [localTempArray count];
NSString* productCount = [NSString stringWithFormat:#"%i", iNumberofArrayProducts];
NSLog(#"The NUMBER OF TmpTable PRODUCTS is %#",productCount);
//Sum the selling price of the records in the _manualBCtemporaryCartArray26
amountSum = [localTempArray valueForKeyPath:#"#sum.lTotalSellingPrice"];
NSLog(#"The total TmpTable SELLING PRICE is %#",amountSum);
NSNumberFormatter * formatter = [[NSNumberFormatter alloc]init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2]; // Set this if you need 2 digits
[formatter setMinimumFractionDigits:2]; // Set this if you need 2 digits
NSString * newString = [formatter stringFromNumber:[NSNumber numberWithFloat:[amountSum floatValue]]];
NSLog(#"FORMATTED MONTHLY SALES IS,R%#",newString);
//This is a hack that replaces the comma with a dot. I want to display the Price as R2 000.10
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#"/:,"];
newString=[[newString componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: #"."];
NSString *item = [NSString stringWithFormat:#"R%# (%i)",newString, iNumberofArrayProducts];
/**********Play audio to warn user that item was added to cart*******/
// ivar
SystemSoundID mBeep;
// Create the sound ID
NSString* path = [[NSBundle mainBundle]
pathForResource:#"scanBarCode" ofType:#"mp3"];
NSURL* url = [NSURL fileURLWithPath:path];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &mBeep);
// Play the sound
AudioServicesPlaySystemSound(mBeep);
// Dispose of the sound
//AudioServicesDisposeSystemSoundID(mBeep);
/**********END - Play audio to warn user that item was added to cart*******/
//When user scans the barcode, we want to display the product that was just scanned. This allows user to see what product they just scanned as it is automatically loaded on the shopping cart. Put IF Statement so this code only executes after the scanning barcode.
[self.searchDisplayController setActive: YES animated: YES];
//self.searchDisplayController.searchBar.hidden = NO;
self.searchDisplayController.searchBar.text = [NSString stringWithFormat:#"%i",fklInventoryID];
[self.searchDisplayController.searchBar becomeFirstResponder];
[self.searchDisplayController.searchBar resignFirstResponder];
NSLog(#"BUTTON ITEM IS,%#",item);
[manualTotalPriceBtn setTitle: item forState: UIControlStateNormal];
/*************************************END - Refresh Displayed Total********************/
}
Try this:
[manualTotalPriceBtn setAttributedTitle:nil forState:UIControlStateNormal];
[manualTotalPriceBtn setTitle:item forState:UIControlStateNormal];
If you are using a xib file the IB will set your value for the attributedTitle instead of the title.
try changing button type from system to custom.
Check that you update the button on the mainthread. If your method is called from a callback of whatever bluetooth scanner module you are using, it might be happening on a backround thread. This will cause button to sometimes update, sometimes it will not, or later.
If not, check the superview property of the button to not be nil. Maybe somewhere in your code you create a bew button, add it to the superview but forgot update your property to point to it (or some other scenario where you update a button that is not inserted in the view).

Get all inside NSDictionary into a UITextView

I got a NSDictionary and I want to print it into a UITextView.
I tried using this code, but when I try to get it into a UITextView it gets only one line of text, when I NSLog it it works perfectly.
for(int i=0; i<[array count];i++) {
dictionary = [array objectAtIndex:i];
//that shows only one line from the dictionary in the textview
textview.text = [dictionary objectForKey:#"text"];
//that shows all the dictionary with key "text" in the log
NSLog(#"%#", [dictionary objectForKey:#"text"]);
}
is there a way to solve this problem?
you should append it to the existing text
textview.text = #"";
for(int i=0; i<[array count];i++)
{
dictionary= [array objectAtIndex:i];
//that shows only one line from the dictionary in the textview
textview.text = [textview.text stringByAppendingFormat:#"%#\n",[diction objectForKey:#"text"]]];
//that shows all the dictionary with key "text" in the log
NSLog(#"%#",[diction objectForKey:#"text"]);
}
The problem is that textview.text is overwriting the previous contents of textview.text.
What you need to do is append the string to the existing value of textview:
textview.text = [textview.text stringByAppendingString:[diction objectForKey:#"text"]];
But this will get all the values side by side, so you may want to add a space in between the values:
NSString *appendedText = [NSString stringWithFormat:#"%# %#", textview.text, [diction objectForKey:#"text"]];
textview.text = appendedText;
Finally, you can use modern Objective-C literals to access your dictionary objects like array[i] and diction[#"text"] instead of using objectAtIndex and objectForKey to type a little less.

How can I show all of objects in NSMutable Array on text field?

I want to show all objects in mutable array on to textfield, label, something else except NSLog
- (IBAction)purchasePressed:(id)sender {
NSMutableArray *addItem = [[NSMutableArray alloc] init];
[addItem addObject:#"Almond"];
[addItem addObject:#"Choc"];
"number" is my label (I'm not sure that all of Objects in MutableArray can be showed on textfield or not?) i can do it only with NSLog.
for (i = 0;i < [addItem count] ; i++ )
{
NSLog(#"%#", addItem);
NSString *test1=(#"%#", addItem);
number.text=test1;
}
Every time you set the text of a label you replace the previous text.
Try replacing your whole loop with something like:
number.text = [addItem componentsJoinedByString:#", "];
Which will create a single string from all of the strings in the array and add that to the label. You could do something similar in your loop if you want to.
If you want a string with all the values concatenated:
NSString *mainString = [NSString alloc] init];
for (NSString *item in addItem) {
mainString = [mainString stringByAppendingString:item];
}
number.text = mainString;
EDIT: Using NSMutableString
NSMutableString *mainString = [[NSMutableString alloc] init];
for (NSString *item in addItem) {
[mainString appendString:item];
}
number.text = mainString;

Saving Hebrew text to NSUserDefaults return strange encoding

I'm saving Hebrew text to NAMutableArray, then I save it to NSUserDefalts, this way:
numOfWallPosts++;
NSString *tempKeyToStore = [NSString stringWithFormat:#"wall_post_%d", numOfWallPosts]; // wall_post_%d
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray addObject:currentOwner];
[tempArray addObject:currentTitle];
[tempArray addObject:currentText];
[tempArray addObject:currentDate];
[tempArray addObject:currentTime];
[tempArray addObject:currentImageURL];
[tempArray addObject:currentWallID];
[self.sharedPrefs setObject:tempArray forKey:tempKeyToStore];
[self.sharedPrefs synchronize];
When I want to get the Hebrew text back I get text like this:
Wall messages: (
"\U05de\U05e2\U05e8\U05db\U05ea",
"\U05ea\U05e8\U05d2\U05d9\U05dc \U05e4\U05d9\U05e7\U05d5\U05d3 \U05d4\U05e2\U05d5\U05e8\U05e3",
"\U05d0\U05d6\U05e2\U05e7\U05ea \U05ea\U05e8\U05d2\U05d5\U05dc \U05d1\U05e9\U05e2\U05d4 19:05",
"27/05/13",
"13:16",
"http://blabla......",
9
)
I tried to format the text in UTF8String, and with NSUTF8StringEncoding and I still get the text this way.
Can I save the text in proper way or encode it back to proper Hebrew?
EDIT:
This is so strange, although the text saved strange, I pull it back and I get the text correctly.
But when I save them to NSUserDefaults, it show me this strange encoding.
NSString *tempKeyToStore = [NSString stringWithFormat:#"wall_post_%d", indexPath.row];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
NSLog(#"\n\nWall messages: %#", [self.sharedPrefs objectForKey:tempKeyToStore]);
tempArray = [self.sharedPrefs objectForKey:tempKeyToStore];
NSString *tempOwner = [tempArray objectAtIndex:0];
NSLog(#"\n\nOWNER: %#", tempOwner);
If you use NSLog(#"%#", ...) to print the description of an array or dictionary, all non-ASCII characters are printed using a \Unnnn escape sequence:
NSArray *a = [NSArray arrayWithObject:#"מערכת"];
NSLog(#"%#", a);
Output:
(
"\U05de\U05e2\U05e8\U05db\U05ea"
)
(The reason is that the description method of NSArray and NSDictionary
uses the Old-Style ASCII Property Lists format,
which, as the name indicates, allows only ASCII characters.)
If you print the description of a string, all characters are properly displayed:
NSLog(#"%#", [a objectAtIndex:0]);
Output:
מערכת
So this is only a display issue.
Try doing something like this:
NSString *someObject = //your object that needs decode
NSString *decodedObject = [NSString
stringWithCString:[someObject cStringUsingEncoding:NSUTF8StringEncoding]
encoding:NSNonLossyASCIIStringEncoding];
NSLog(#"decodedObject = %#", decodedObject);
Edit: There's probably something wrong in your code someplace else because this:
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray addObject:#"בדיקה"];
[[NSUserDefaults standardUserDefaults] setObject:tempArray forKey:#"test"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSMutableArray *test2=[[NSUserDefaults standardUserDefaults] objectForKey:#"test"];
NSLog(#"test2: %#",[test2 objectAtIndex:0]);
works fine.
Well, can you post the code behind sharedPrefs?
When i tried to save a simple hebrew to userdefault it worked just fine.
NSString *tempKeyToStore = #"KEY";
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray addObject:#"שלום שלום"];
[[NSUserDefaults standardUserDefaults] setObject:tempArray forKey:tempKeyToStore];
[[NSUserDefaults standardUserDefaults] synchronize];
Read it later -
//
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *tempArray = [defaults objectForKey:#"KEY"];
for (NSString* str in tempArray)
{
NSLog(#"%#", str);
}
Hope i helped..

Resources