This question already has answers here:
Passing data between view controllers
(45 answers)
Closed 8 years ago.
I am new to iOS development, but this is a question which I have a lot of trouble with and could help others.
I need to pass a simple integer variable between two views. This is an example of a variable I need to pass:
int tally = 1;
People talk about messing with delegates and protocols to pass data between views, but frankly, that is all a bit over my head. Is there an easier way to pass simple variables such as integers between two view controllers?
Thank you kindly for any responses!
#interface View1:UIView
#property int passingInt;
#end
#interface View2:UIView
#property int passingInt;
#end
Now, you can directly set the variables like,
view1.passingInt=view2.passingInt;
or
view1.passingInt=100;
Although these are not the correct ways to do this kind of stuff I'll give you two different methods.
Create a global variable in a class header file, say CommonVar.h.
You can now use this variable with anything that has this header file imported
//CommonVar.h
int foo;
//This is the entire file
Now if you import this file in any class, you can use foo directly.
The other method is to use singletons and their variables. You can read about them here http://www.galloway.me.uk/tutorials/singleton-classes/
I am telling again this is not the correct way to do this but I think you will find them simple than handling delegates.
Related
This question already has answers here:
Using self->ivar when accessing instance variables directly
(4 answers)
Closed 7 years ago.
So if I have in iOS (with Objective C, not sure if this the same for Swift) e.g.
#property (nonatomic, copy) NSString *aString;
And then some where in the code I have
// Simple ivar access in some method
_aString = anyStringOrNil;
// Self-> ivar access in some other method
self->_aString = anyStringOrNil;
I would like to know the differences between using one or the other
As you posted, those are identical. There is a difference between directly accessing the ivar and going through a property however. If you set the string as so:
self.aString = someString;
That would go through the automatically generated setter which, based on your property declaration would make a copy of someString. This is preferable in the case of working with mutable strings. You don't want the string to change out from under you. In both examples that you used, you are directly setting the value of _aString to the string reference, so if the string is a mutable string that is owned by someone else, it could change without warning and lead to unexpected results.
It is generally better practice to go through the setter (self.property = foo) rather than directly accessing the ivar as it is possible that the setter for the property has some behavior you may want and directly accessing it bypasses this. Of course, there are situations where accessing the ivar directly is required, but it is best to go through the property as a default.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm a student in a internship, and i'm learning Objective-C in order to develop an IOS application. They already had an existing base of code, but some part of the code give me problems.
As the previous developer isn't in the company anymore, and because no one else know about Objective-C, no one can answer some of my questions about how the application is built, so I can't determine if it is that i don't understand, or if it's just bad practices.
Here are these questions :
1°) In some classes, i found code like this :
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated] }
This code is useless, right ?
2°) In like 9/10 methods in the project, they return (void). Is it a common pratice in Obj-C (because everything is a pointer) ?
3°) Sometimes there is the interface declaration in both header and messages files. I guess it's because you want to declare only a part in header for a future include, and to have a "private" part. But in a file, i find the following code :
In header :
#interface WebViewController : UIViewController
#properties ...
#end
In Msg file :
#import ...
#interface WebViewController ()
#end
#implementation WebViewController ...
What's the point declaring a void interface a second time in the msg file ?
4°) More, in another class, the interface is declared a second time too, but a method is defined (in the msg file). What's the point as the method is defined bellow, and is not declared in the header file ?
thank you in advance
Welcome to Objective-C :)
Not necessarily. The super class may have specific behaviour defined in it's own method implementation that would cause an issue if you didn't call it. Overriding methods means the super classes own method won't be called by default.
Added from comment: Of courser if you didn't override it then the superclass definition would get called just fine. There are 2 common reasons why you would find it overridden:
a. It's in the Xcode template so it has always been there and not been removed
b.it used to have other content but it was deleted and the method call left behind.
Yes. Although you don't explicitly return void in the method, you do need to specify some return type. If you're not returning anything then void is the right value. It's found commonly in obj-c classes as the method may respond to being called by mutating an internal ivar or property and not require a return. Alternatively the result might be to send a notification so a return value is not needed. Increasingly the use of block-based completion handlers replaces explicit value return as a way to respond to the contents of a method.
Yes, it's to give a private interface that you don't want exposed. In the case where there's nothing in the private interface it's probably there because it came with the template code from Xcode and no one removed it. You can ignore or remove.
For the one you mention with a method, while it's not required to declare private methods in an interface it makes sense from the point of view of writing readable code (a strongly endorsed concept in obj-c). Since the compiler will remove any unnecessary code it makes no difference to declare it and makes the task of reading the code and understanding the class that much easier when you or someone else returns to it later. It's a also a good place to put documentation in comments as it groups it all together.
Hope that helps. Check out the Objective-C programming guides from Apple to for more best practice tips.
1). Yes you can delete this method
2). It depends upon your requirement, whether you want a return type or not. e.g.
- (BOOL)isEmptyOrNull:(NSString*)str;
3). These are called extensions, you can read more about it here http://rypress.com/tutorials/objective-c/categories.html
Extensions are used to hide the methods from out side world(by saying hide I mean you can't find those methods with your eyes)
4). Methods define in implementation file are not visible to a programmer, it's just like private methods in java but in ObjC there is no such thing like private method. Read this thread for private methods Best way to define private methods for a class in Objective-C
This question already has answers here:
Why should I use #properties? [duplicate]
(3 answers)
Closed 9 years ago.
Let say I have:
#interface test : NSObject {
BOOL bVal;
}
People keep saying properties are a better way of accessing a ivar, but are they doing it just for the heck of it?
Why would I need a #property for this ivar in this case?
I'm just wondering if people know why they are doing what they are told to, or if I'm missing something.
Properties get you some nice things, like synthesized getters and setters which are sure to be written in the best way for the property's retain/strong, assign/weak, atomic or non-atomic attributes. If you don't need code outside your class accessing the ivar at all then you should probably declare the ivar in the implementation itself and keep it completely hidden from the outside, like:
#implementation test {
BOOL bVal;
}
The answer to your other question is that it depends on the person, of course. Yes, there are plenty of people on this site parroting advice and code snippets without really understanding them. There are also plenty of people on here who really know what they're talking about.
I know this could be a noob question but I am a bit stucked here. I usualy makes the following to access app data in different ViewControllers: First I declare a global.h module like this
global.h
typedef struct {
NSString *appName
NSString *appVersion;
bool mode;
} structApp;
extern structApp app;
After that I declare in MainViewController.h the struct so that I can access data
#implementation ViewController
structApp app;
- (void)viewDidLoad
{
app.appVersion = #"v1.02";
}
#end
And then I include "global.h" in every ViewController.h
This way I can access globally. As far I can see this is a good implementation and I have used it in more than 20 apps. Problem starts when this struct grows in size. In those cases I see corrupted memory, nil variables that were previously loaded with data, etc.
There is a better way of making data available in all ViewController? Please give me some examples if you can.
You have two options
Use a singleton class - Refer Objective C Singleton
Declare properties in App delegate - Refer SO
You can access the app delegate from any class using:
AppDelegate *appDel = [[UIApplication sharedApplication] delegate];
As you were using extern in your structure, any object updating the same value.
In OOPS, global variables are never said Good, so you need to use a singleton pattern.
Create a singleton/shared class having all those stuffs in your structure and use it.
You should deal with struct only if you deal with primitive data (if you are in a OOP way).
app.appVersion = #"v1.02";
Make your struct pointing on dangling pointer, since you are pointing a data in a function scope (app.appVersion is only holding the pointer, not the data). So you must retain all those object values in order to make it content safe, but i must admit it is still a Q&D approach.
If you need global access to data, you can use a singleton, only if you really need strong encapsulation and control to data.
How to make a singleton
What should my Objective-C singleton look like?
You can use macro too, that way you'll can use constants string without worrying data persistency, since they will always be available into the scope you are dealing with.
If you only want to read the data and you dont need any complex data structure you can also use a settings file like
Settings.h
#define appName #"blabla"
#define appVersion #"1.01"
#define mode 1
In General using struct should work fine. There is nothing wrong with using them. If you observe weird values caused by overlapping memory or illegal re-use of it or so then your problem is somewhere else but not in using structs in principle. The extern statement could lead to such an issue.
A class is not much more than a struct too, from a memory usage perspective. If I were you I would design a class with properties where ever you have members when using a struct. And make use of them in pretty the same way.
For "global variables" I apply a singleton pattern. That is basically a class with a class method (the leading + instead of -) that makes the one and only instance of the class available. Within that method I check if the class (a class internal static reference to the same class) is already available (!= nil) and instantiate it. Sometimes I use the initialize method for that. Initialize is an objective-c typical thing. It is called only once for each class, even subclassed ones, when or before the class is used for the first time. A very good place for instantiating class variables as singletons but not portable to other programming languages.
I am making a multiple choice quiz app. In my main class, I have an integer called "points" that is used to display the current points earned in the quiz view. However, I also want to display the points in the view of another class, which tells the user that his answer is correct.
I know that you can do this if one class is a subclass of the other, but can you do it if they are not related?
One way to do this is to set up points as a global variable. Like so:
In your AppDelegate.h file insert this line after the #end:
extern int points;
In any classes that needed to read/write to points, in the .h files after the #end, add this line:
int points;
I would look into something like Singleton Objects
This link provides a basic example of simple Singleton Objects, which you could use to share a variable between classes.