I have surfed quite a lot about this. But the results that I've got tells me that either I should use appDelegate or singleton etc.
All of which produces the same result. i.e I am able to share a variable in different ViewControllers but as soon as the ViewController gets changed , the variable looses it's value.
For example I used a variable named myVar of type int. I declared it in AppDelegate and then I'm able to use it in all the ViewControllers with the help of AppDelegate. But as soon as I move from A ViewController to B ViewController the value of the myVar variable gets "0" again. I don't want that . I want the variable to hold it's value. And I don't want to pass this data with the help of pushViewController etc. Please suggest me a good solution.
AppDelegate.h
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (strong, assign) int myVar;
#end
FirstViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
AppDelegate* app = (AppDelegate*)[UIApplication sharedApplication].delegate;
app.myVar = 1;
NSLog(#"%d",app.myVar); //Shows "1" in Log
}
SecondViewController.m
- (IBAction)pressButton:(id)sender{
AppDelegate * app = (AppDelegate*)[UIApplication sharedApplication].delegate;
NSLog(#"%d",app.myVar); // Shows "0" in Log (But I want it to show "1" as I have already set "myVar" value as "1" in my FirstViewController)
}
Your #property (strong, assign) int myVar; is declaring both strong and assign. As an int, it should only be assign, not strong. strong would be used for Objective-c objects, assign for primitive C properties.
I think what you want is the following:
#property (assign, nonatomic) int myVar;
First of all check your code there are some error
AppDelegate.h
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (nonatomic, assign) int myVar;
And check it gives same value in FirstViewController.m and SecondViewController.m
if your var is a NSString, you can simple use the [copy] protocol. e.g.
NSString *eString = [cString copy];
If it is an object, you need to implement the [copy] protocol for that class.
Related
I'm developing for iOS 7 but I still have to manually write getters otherwise my properties just don't get initialized. I tried to manually synthesize those properties, even though that shouldn't be needed anymore, but that doesn't do it.
In my view controller below, I use the property motionTracker, which never gets initialized. I have the same issue with all my projects, so I know it's a misunderstanding on my part.
#import "ViewController.h"
#import "TracksMotion.h"
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UIButton *startRecording;
#property (weak, nonatomic) IBOutlet UIButton *stopRecording;
#property (strong, nonatomic) TracksMotion *motionTracker;
#end
#implementation ViewController
#synthesize motionTracker = _motionTracker;
- (void)startMyMotionDetect
{
[self.motionTracker startsTrackingMotion];
}
#end
The motionTracker has a public API for the method startsTrackingMotion so I don't know why this doesn't work.
#import <Foundation/Foundation.h>
#import <CoreMotion/CoreMotion.h>
#interface TracksMotion : NSObject
- (void)startsTrackingMotion;
- (void)stopTrackingMotion;
#property (strong, nonatomic) CMMotionManager *motionManager;
#end
Properties / instance variables are not magically initialized for you. When you say:
#property (strong, nonatomic) TracksMotion *motionTracker;
... you are just reserving memory space for an instance variable (and generating a getter and a setter method through #synthesize or autosynthesis). There is no actual TracksMotion object there until you put one there. You must write code to do that. You must create or obtain a TracksMotion instance and assign it to self.motionTracker at some point, presumably early in the life of self (in this case, that's a ViewController instance). Until you run code that does that, self.motionTracker is nil.
(It is possible that you are being confused because it looks like outlets are automatically initialized. For example, you've got #property (weak, nonatomic) IBOutlet UIButton *startRecording; And sure enough, self.startRecording is a button. But that's because the nib-loading process does for you the very thing I'm saying you must do: it makes a button from the storyboard or .xib file, and assigns it to this instance variable.)
I'm going through a tutorial on core-data in Objective-C and can't understand the following syntax:
#interface RootViewController : UITableViewController <CLLocationManagerDelegate> {
NSMutableArray *eventsArray;
NSManagedObjectContext *managedObjectContext;
CLLocationManager *locationManager;
UIBarButtonItem *addButton;
}
#property (nonatomic, retain) NSMutableArray *eventsArray;
#property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain) CLLocationManager *locationManager;
#property (nonatomic, retain) UIBarButtonItem *addButton;
#end
We have four properties here that are declared in the implementation file, which to my understanding means they are private. What exactly is happening within the curly brackets? Why are these variables put there? And also, is it a class extension? I see () are missing here so probably it is not. What is this kind of syntax called then?
Its not a category.Its just a class named RootViewController which extends UITableViewController and implements protocol CLLocationManagerDelegate.
Coming to your braces ->
generally if you don't create iVars in curly braces, by default they are created with underscore as prefix to them. This is done by compiler.
But here, you explicitly said, that the ivar should be without underscore(_).
Any you should synthesize them as below or else it will give a warning.
#synthesize eventsArray= eventsArray;
It's just a regular definition of a RootViewController class, the #interface doesn't necessarily have to be in a header file, private classes (that shouldn't/don't need to be accessible elsewhere) can also be defined directly in the .m file.
The definitions in the curly braces are just regular instance variables of the RootViewController class.
What you have is called the class interface. It is just the .h file of your program files. .If you want a class category, just do
#interface RootViewController (CategoryName)
and for an extension, inside the .m type
#interface RootViewController ()
#end
#implementation
Variables between curly braces:
{
NSMutableArray *eventsArray;
NSManagedObjectContext *managedObjectContext;
CLLocationManager *locationManager;
UIBarButtonItem *addButton;
}
are just usual variables.
For variable, defined with #property base word:
#property (nonatomic, retain) NSMutableArray *eventsArray;
#property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain) CLLocationManager *locationManager;
#property (nonatomic, retain) UIBarButtonItem *addButton;
created accessor and mutator methods. And also you can define options for those variables in bracers. Plus you can get local synonym for them, using base word #synthesize in .m file, like
#synthesize addButton = myLovelyButton;
then you can use myLovelyButton in .m file instead addButton
Both of these definition do not belong to the category.
For define category just type code like:
#interface <#className#> (<#categoryName#>)
{
//optional variables here
int i;
NSString *s;
}
//optional variables here
#property NSString *str;
//optional methods here
-(void)doSomething;
#end
Then you can implement your methods and use these variables:
#implementation <#className#> (<#categoryName#>)
-(void)doSomething
{
int i = 0;
str = #"blah";
s = #"wow";
NSLog(#"%i - %# - %#",i,str,s);
}
#end
Use that for add your methods to existing classes.
Variables inside brackets directly after the #interface or #implementation are instance variables. These are variables associated with each instance of your class, and thus accessible anywhere in your instance methods.
If you don't put the brackets, you declare global variables. Any variable declared outside of any bracket block will be a global variable, wether these variables are before or after the #implementation directive. And global variables are evil and needs to be avoided at all costs (you can declare global constants, but avoid global variables), especially because they are not thread-safe (and may thus generate bugs that are a mess to debug).
#interface YourClass : ParentClass
{
// Declare instance variables here
int ivar1;
}
// declare instance and class methods here, as well as properties (which are nothing more than getter/setter instance methods)
-(void)printIVar;
#end
// .m
int someGlobalVariable; // Global variable (bad idea!!)
#implementation YourClass
int someOtherGlobalVariable; // Still a bad idea
-(void)printIVar
{
NSLog(#"ivar = %d", ivar1); // you can access ivar1 because it is an instance variable
// Each instance of YourClass (created using [[YourClass alloc] init] will have its own value for ivar1
}
Only modern compilers let you declare instance variables (still in brackets) also inside either your class extension (#interface YourClass () in your .m implementation file) or in your #implementation, in addition to the possibility to declare them after the #interface in your .h. The benefits being to hide those instance variables from external users of your classes, by declaring them in the .m file and not in the .h file anymore, because users of your class don't need to be aware of the internal coding details of your class, but only needs to know the public API.
One final advice: instead of using instance variables, Apple more and more recommends to use #property directly, and let the compiler (explicitely using the #synthesize directive, or implicity with modern LLVM compilers) generate the internal backing variable. So that at the end you generally won't need to declare instance variables at all, and thus omit the empty { } after the #interface directive:
// .h
#interface YourClass : ParentClass
// Declare methods and properties here
#property(nonatomic, assign) int prop1;
-(void)printProp;
#end
// .m
#implementation YourClass
// #synthesize prop1; // That's even not needed with modern LLVM compiler
-(void)printProp
{
NSLog(#"ivar = %d", self.prop1);
}
I have a view controller that needs one of its ivars to call a method on it at some point. Is it acceptable for the ivar to store a reference to its owner? Could this cause any problems? If so, better way?
// From MainViewController.h
#import <UIKit/UIKit.h>
#import "MyObject.h"
#interface MainViewController : UIViewController
#property (strong, nonatomic) MyObject *myObject;
#end
// From MyObject.h
#import <UIKit/UIKit.h>
#interface MyObject : NSObject
#property (strong, nonatomic) id myOwner;
#end
When 2 objects have strong references to each other that will create retain loop - so they will never get deallocated (and so you will get memory leak) unless you manually break the loop (e.g. set myObject property to nil on viewWillDisappear if appropriate).
Much better way will be that "child" object will have weak reference to its "owner" so you won't have retain loop at all:
#interface MyObject : NSObject
#property (weak, nonatomic) id myOwner;
#end
Yes, but you want to think about changing the property declaration to:
#property ( weak, nonatomic ) id myOwner;
This way you avoid a possible retain cycle.
a block could do the trick too.
I have a singleton I implement in this way:
PhotoViewController* sharedSingleton = [PhotoViewController sharedManager];
I know that to launch a method I have to do [sharedSingleton method];
but what if I want to change an integer declared in the PhotoViewController.h file as NSInteger* tagNumber, hoe can I do that? I tried this:
[sharedSingleton.tagNumber = 1];
but it doesn't work!
EDIT:
error: property tagNUmber not found on object of type photoViewController
#interface PhotoViewController : UIViewController{
BOOL newMedia;
UIPopoverController *popoverController;
DBRestClient *restClient;
NSInteger* tagNumber;
}
+ (PhotoViewController *) sharedManager;
#end
Singletons are regular objects. The only difference is that only one instance will be created from the class.
If you aren't able to set the tagNumber it is likely that some other type of coding error is happening... perhaps the tagNumber property was declared in a class extension, making the accessor/mutator methods private?
If you edit your question with how the tagNumber is declared, and also include the error message you are getting, I'll be able to edit this answer and give you more specific advice.
EDIT: ...and yes, definitely double check to make sure you didn't declare the NSInteger to be a pointer... an NSInteger is a scalar type (so it takes a direct value, and doesn't use the dereference '*' operator).
I suggest using properties instead of accessing the instance variables directly:
#interface PhotoViewController : UIViewController
#property (nonatomic, assign) BOOL newMedia;
#property (nonatomic, strong) UIPopoverController *popoverController;
#property (nonatomic, strong) DBRestClient *restClient;
#property (nonatomic, assign) NSInteger tagNumber;
+ (PhotoViewController *) sharedManager;
#end
Then set the variable without the brackets as:
sharedSingleton.tagNumber = 1;
For example one, I declare an object inside the interface brace {} like:
#interface testViewController : UIViewController {
IBOutlet UILabel * myLabel;
}
#property (retain, nonatomic) UILabel *myLabel;
#end
and example two, I declare an object outside the inferface brace {} like:
#interface testViewController : UIViewController {
}
#property (retain, nonatomic) IBOutlet UILabel *myLabel;
#end
I run the code and the result is the same, so I want to ask what is the different for decalare an object inside or outside the interface brace {}?
Thanks
The modern Objective-C runtimes (64-bit Mac OS X and iOS) will generate the backing store for your declared properties when you #synthesize them. So you don't need to declare them within the braces.
If you are declaring an iVar that is not a property and will only be used by the class, then they need to be declared. It's a good idea to mark these #private e.g
#interface MyClass : NSObject {
#private
NSString *privateString;
}
#property (nonatomic, copy) NSString *publicString; // be sure to #synthesize this
#end
In the second example you only declare a property. Xcode will declare object automatically.