NSDictionay display - ios

im not able to display the values from this code .plz provide a code to display the mutabledictionay and a
- (void)viewDidLoad{
[super viewDidLoad];
mdict =[[NSMutableDictionary alloc]init];
[mdict setValue:#"abc" forKey:#"def"];
[mdict release];
}
-(void)display{
CFShow(mdict);
}

What about using
-(void)display{
NSLog(#"%#",mdict);
}
Change your method as:
- (void)viewDidLoad{
[super viewDidLoad];
mdict =[[NSMutableDictionary alloc]init];
[mdict setValue:#"abc" forKey:#"def"];
//if you want to display use following statement
[self display];
// [mdict release];//you should not release it here.
}
NOTE: In viewDidLoad you are using [mdict release]; mdict will be released!!!
this should not be in viewDidLoad, put that statement in dealloc.

First You need to create NSMutableDictionary is Public (declare in .h file) because you use it in outside and release its instance in dealloc method
- (void)viewDidLoad{
[super viewDidLoad];
self.mdict =[[NSMutableDictionary alloc]init];
[self.mdict setValue:#"abc" forKey:#"def"];
[self display];
}
-(void)display
{
NSLog(#"%#",[self.mdict objectForKey:#"def"]);
}
and release instance of dictionary in -(void)dealloc method

Related

How to call a function that is found in a specific view controller at the moment the application is launched?

I have some functions in my SecondViewController.m file and I want to call these functions when the application is launched. I have tried to do it like this, but it’s not working.
I have put a print statement in the function to see if it is getting called or not and it appears that the print statement is executed correctly.
Here is the following code:
In SecondViewController.h:
#interface AlertsManagementController : UIViewController {
PushNotificationSettings *pushNotificationSettings;
IBOutlet UISwitch *switch1;
IBOutlet UISwitch *switch2;
}
#property (nonatomic, retain) PushNotificationSettings *pushNotificationSettings;
In SecondViewController.m:
- (void)viewDidLoad {
[super viewDidLoad];
appDelegate = (projectAppDelegate *)[[UIApplication sharedApplication] delegate];
pushNotificationSettings = [[PushNotificationSettings alloc] init];
NSDictionary * settings = [pushNotificationSettings getPushSettings];
}
-(void)modificationPush
{
if (switch1.on && switch2.on)
[switch2 setOn:NO];
printf("Function 1 executed!");
}
-(void)sendTokenFunc{
NSMutableDictionary *preferences1 = [[NSMutableDictionary alloc] init];
if (switch1.on)
[preferences1 setObject:#"1" forKey:#“switch1”];
else
[preferences1 setObject:#"0" forKey:#“switch1”];
if (switch2.on)
[preferences1 setObject:#"1" forKey:#“switch2”];
else
[preferences1 setObject:#"0" forKey:#“switch2”];
[pushNotificationSettings savePushSettingsWithDictionary:preferences1];
[preferences1 release];
[appDelegate uploadToken:[appDelegate tokenValue]];
printf("Function 2 executed!");
}
In appDelegate.m:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
SecondViewController * vc = [[SecondViewController alloc]init];
[vc modificationPuch];
[vc sendTokenFunc];
}
This can be done by using NSNotificationCenter.
First go to your SecondViewController.m file and in viewDidLoad write the following code.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(myNotification:) name:#"myNotification" object:nil];
Then outside viewDidLoad make a function myNotification. I will show you the eg below
-(void)myNotification:(NSNotification*)notification
{
//write the code you wanna excecute when the app opens here
}
Go to appDeligate.m and write this code in application didFinishLaunchingWithOptions
[[NSNotificationCenter defaultCenter] postNotificationName:#"myNotification" object:self userInfo:nil];
Thank you,
Happy coding;)
But if SecondViewController didn't inited, you must get EXC_BAD_ACCESS :)

TableView not showing new data loaded from plist after dismissing from other view

My First View is a UIViewController i have a UITable View in it and it works just fine.
From the first view i push another view, in that view i select a group name then the view dismiss, what i want is when i select the group name from the second view the first view loads the values of that group name to the table view, this is the code i use and its not working
the second view code
- (IBAction)sendNames:(id)sender {
if (!keyValue) {
NSLog(#"Didnt Select Any Group To Send");
return;
}
ViewController *theInstance = [[ViewController alloc] init];
[theInstance setGroupName:keyValue];
[theInstance ReceivedGroup:nil];
[self dismissViewControllerAnimated:YES completion:nil];
//tried that option and didnt work too, i added the rest of the code in the viewDidLoad
//[[NSNotificationCenter defaultCenter] postNotificationName:#"RG" object:nil];
}
keyValue is NSString that been set on tableView didSelectRowAtIndexPath
the first view
- (IBAction)ReceivedGroup:(id)sender {
NSString *path = [self dataFilePath];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSArray *tempArray = [dict objectForKey:groupName];
nameArray = [[NSMutableArray alloc] init];
[nameArray addObjectsFromArray:tempArray];
[nameTable reloadData];
NSLog(#"Group Name : %#",groupName);
NSLog(#"Array : %#",nameArray);
}
groupName is NSString
In the log i get the groupName and the nameArray printed
but the tableView is empty.
EDIT: I fixed the problem and posted my answer
Your viewcontroller "theInstance" will be deallocated immediately after calling sendNames: so nothing's gonna happen. You should rather pass a pointer of your first viewcontroller to your second viewcontroller (e.g. set it as a property) and perform all operations on this viewcontroller.
subclass UITableViewController
#interface SecondViewController : UITableViewController
#property (nonatomic, strong) ViewController *firstViewController;
#end
if using storyboard segues implement in your first viewcontroller :
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
((SecondViewController *) segue.destinationViewController).firstViewController = self;
}
sendNames: should then look like this:
- (IBAction)sendNames:(id)sender {
if (!keyValue) {
NSLog(#"Didnt Select Any Group To Send");
return;
}
ViewController *theInstance = self.firstViewController;
[theInstance setGroupName:keyValue];
[theInstance ReceivedGroup:nil];
[self dismissViewControllerAnimated:YES completion:nil];
//tried that option and didnt work too, i added the rest of the code in the viewDidLoad
//[[NSNotificationCenter defaultCenter] postNotificationName:#"RG" object:nil];
}
I Fixed it by sending the keyValue using NSNotificationCenter
Here is my code now
For The Second View
- (IBAction)sendNames:(id)sender {
if (!keyValue) {
NSLog(#"Didnt Select Any Group To Send");
return;
}
[[NSNotificationCenter defaultCenter] postNotificationName:#"RG" object:keyValue];
[self dismissViewControllerAnimated:YES completion:nil];
}
Then On The First View
- (void)receiveNotification:(NSNotification *)notification {
NSString *Key = [notification object];
nameArray = [[NSMutableArray alloc] init];
[nameArray removeAllObjects];
NSString *path = [self dataFilePath];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSArray *tempArray = [dict objectForKey:Key];
[nameArray addObjectsFromArray:tempArray];
[self.nameTable reloadData];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[nameTable numberOfRowsInSection:0] - 1 inSection:0];
[nameTable scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(receiveNotification:) name:#"RG" object:nil];
}

NSThread Showing SIGABRT

I'm new to IOS I need to implement NSThread in my program, but when it invoked it shows an SIGABRT error. my current code is given below
XMLParser.m
-(void)loadXML
{
categories =[[NSMutableArray alloc]init];
NSString *filepath =[[NSBundle mainBundle]pathForResource:#"cd_catalog" ofType:#"xml"];
NSData *data =[NSData dataWithContentsOfFile:filepath];
parser=[[NSXMLParser alloc]initWithData:data];
parser.delegate =self;
[parser parse];
}
ViewController.m
- (void)viewDidLoad
{
xmlParser =[[XMLParser alloc]init];
NSThread *myThread =[[NSThread alloc]initWithTarget:self selector:#selector(loadXML) object:nil];
[myThread start];
[super viewDidLoad];
}
please tell me what is wrong with my program
Use this code to solve your problem...
ViewController.m
- (void)viewDidLoad
{
NSThread *myThread =[[NSThread alloc]initWithTarget:self selector:#selector(doParsing) object:nil];
[myThread start];
[super viewDidLoad];
}
-(void)doParsing
{
xmlParser =[[XMLParser alloc]init];
[xmlParser loadXML];
}
Instead of creating a NSThread object you can start a thread using
//performSelectorInBackground:withObject: is NSObject's method
[self performSelectorInBackground:#selector(loadXML) withObject:nil];
I didn't find any buggy code but enable NSZombie and seee which object is causing this.
loadXML is not define on ViewController so your thread code should be changed to use an instance of XMLParser instead of self like so:
XMLParser *parser = [[XMLParser alloc] init];
NSThread *thread = [[NSThread alloc] initWithTarget:parser selector:#selector(loadXML) object:nil];
[thread start];
Since Apple introduced GCD, you may solve it without creating any NSThread instance.
dispatch_async(dispatch_get_global_object(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self loadXML];
});

What to replace [reader dismissModalViewControllerAnimated :NO with?

I am using XCode v.4.6 and I am trying to make an app that uses a QR Code scanner. I have followed a tutorial on this page ( http://iphonenativeapp.blogspot.com/2011/07/qr-code-readerscanner-for-iphone-app-in.html ) and have copied and pasted this code:
#import "QRscannerFirstViewController.h"
#interface QRscannerFirstViewController ()
#end
#implementation QRscannerFirstViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"First", #"First");
self.tabBarItem.image = [UIImage imageNamed:#"first"];
}
return self;
}
- (void)viewDidLoad
{
[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.
}
#import "QRscannerFirstViewController.h"
#end
#implementation QRscannerViewController
#synthesize imgPicker,resultTextView;
-(IBAction)StartScan:(id) sender{
ZBarReaderViewController *reader = [ZBarReaderViewController new];
reader.readerDelegate = self;
reader.readerView.torchMode = 0;
ZBarImageScanner *scanner = reader.scanner;
// TODO: (optional) additional reader configuration here
// EXAMPLE: disable rarely used I2/5 to improve performance
[scanner setSymbology: ZBAR_I25
config: ZBAR_CFG_ENABLE
to: 0];
// present and release the controller
[self presentModalViewController: reader
animated: YES];
resultTextView.hidden=NO;
}
- (void) readerControllerDidFailToRead: (ZBarReaderController*) reader
withRetry: (BOOL) retry{
NSLog(#"the image picker failing to read");
}
- (void) imagePickerController: (UIImagePickerController*) reader didFinishPickingMediaWithInfo: (NSDictionary*) info
{
NSLog(#"the image picker is calling successfully %#",info);
// ADD: get the decode results
id<NSFastEnumeration> results = [info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
NSString *hiddenData;
for(symbol in results)
hiddenData=[NSString stringWithString:symbol.data];
NSLog(#"the symbols is the following %#",symbol.data);
// EXAMPLE: just grab the first barcode
// break;
// EXAMPLE: do something useful with the barcode data
//resultText.text = symbol.data;
resultTextView.text=symbol.data;
NSLog(#"BARCODE= %#",symbol.data);
NSUserDefaults *storeData=[NSUserDefaults standardUserDefaults];
[storeData setObject:hiddenData forKey:#"CONSUMERID"];
NSLog(#"SYMBOL : %#",hiddenData);
resultTextView.text=hiddenData;
[reader dismissModalViewControllerAnimated: NO];
}
#end
into my .m file. When I put this code ino the editor, I get a warning saying how this
[reader dismissModalViewControllerAnimated: NO];
and this
[self presentModalViewController: reader
animated: YES];
has been decapricated in IOS 6.0.
When I run my application and press a button that starts the QR Scanner, my application quits and it gives me the
Thread 1: signal SIGABRT
error and highlights
return UIApplicationMain(argc, argv, nil, NSStringFromClass([QRscannerAppDelegate class]));
What is recommended for replacing this and how should I fix this error?
Here you go
[self presentViewController:reader animated:YES completion:Nil];
[reader dismissViewControllerAnimated:NO completion:Nil];
Use [self presentViewController:reader animated:YES completion:nil]; and [reader dismissViewControllerAnimated:NO completion:nil];

How to add a textfield to an NSMutableArray

I'm trying to present what was entered into a textfield into a nsmutable array that will later be displayed.
I think that the problem is in the -(void)viewDidLoad method but I included all of the code just in case. The catch is that I will be leaving this page and then returning to it after another piece of information is selected. As this happens, I need to keep track of EACH thing that was entered into the textfield. Thanks for any help!
#import "EnteringCoursesViewController.h"
#import "SelectRotationController.h"
#implementation EnteringCoursesViewController
#synthesize classField;
#synthesize indicatedClass;
#synthesize labelClassTitle;
#synthesize selectRotationController;
#synthesize classesEnteredTable;
- (IBAction)chooseType {
UIActionSheet *typeSheet = [[UIActionSheet alloc]
initWithTitle:#"Class types"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:#"Core Class", #"Elective", nil];
[typeSheet showInView:self.view];
[typeSheet release];
}
- (void)actionSheet:(UIActionSheet *)typeSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) {
self.indicatedClass = classField.text;
NSString *indicatedString = indicatedClass;
NSString *greeting = [[NSString alloc]
initWithFormat:#"%# meets 6 times per rotation", indicatedString];
labelClassTitle.text = greeting;
labelClassTitle.hidden = NO;
[greeting release];
[indicatedClass release];
}
else if (buttonIndex == 1) {
self.indicatedClass = classField.text;
NSString *indicatedString = indicatedClass;
NSString *greeting = [[NSString alloc]
initWithFormat:#"%# meets 3 times per rotation", indicatedString];
labelClassTitle.text = greeting;
labelClassTitle.hidden = NO;
[greeting release];
[indicatedClass release];
}
}
- (IBAction)chooseFirstMeeting:(id)sender {
SelectRotationController *selectView = [[SelectRotationController alloc]
initWithNibName:#"SelectRotationController"
bundle:[NSBundle mainBundle]];
[selectView.navigationItem setTitle:#"First Period Day Choose"];
[self.navigationController pushViewController:self.selectRotationController animated:YES];
self.selectRotationController = selectView;
[selectView release];
}
- (IBAction)enteredClassText:(id)sender {
NSMutableArray *classesEntered = [[NSMutableArray alloc] init];
[classesEntered addObject:indicatedClass];
[classesEntered release];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidLoad {
self.navigationItem.hidesBackButton = YES;
[super viewDidLoad];
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[classField release];
[labelClassTitle release];
[indicatedClass release];
[selectRotationController release];
[classesEnteredTable release];
[super dealloc];
}
#end
If viewDidLoad is called "indicatedClass" is not yet initialised and therefore nil.
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html
Important Raises an NSInvalidArgumentException if anObject is nil.
If you want to save that by leaving the view, add the addObject-Call in the viewDidUnload-method. Definitely you should check if the value is nil ;)
I dont see any alloc for your variable indicatedClass but an release!? It might be that the variable doesnt exists if viewDidUnload is calling.
EDIT
You init an NSMutableArray, add the object to this array and after that you released that object. Therefore the Data is away. You must save your array therewith you can use the content later. Keyword: NSUserDefaults ;)
Check also of nil values:
- (IBAction)enteredClassText:(id)sender {
if (indicatedClass != nil) {
NSMutableArray *classesEntered = [[NSMutableArray alloc] init];
[classesEntered addObject:indicatedClass];
[classesEntered release];
}
}
If the sender is an UILabel you can also use this snippet:
- (IBAction)enteredClassText:(id)sender {
if (sender.text != nil) {
NSMutableArray *classesEntered = [NSMutableArray arrayWithObject:sender.text];
// TODO: Save your array to NSUserDefaults...
}
}

Resources