If I have a UIImageView in an .xib file called MainViewController (which, of course, is linked with the respective MainViewController interface (.h) and implementation (.m) files), how can I change the image of the UIImageView from an entirely separate class?
I want to process all of the image initialisation from a separate class (there are a lot of images), but can't seem to figure out how to do it outside of MainViewController.m.
Any tips? Thanks.
Declare these ImageView as #property and access them in other classes.
#property (nonatomic, retain) IBOutlet UIImageView *image1;
In the implementation class
#synthesize image1;
Now you can use setter and getter from other classes to access these objects to play around.
Related
I'm an Objective-C newbie and I'm reading "iPhone programming" by Alasdair Allan. While reading, I found this code:
#interface RootController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
UITableView *tableView;
NSMutableArray *cities;
}
// warning: remember this tableView
#property (nonatomic, retain) IBOutlet UITableView *tableView;
The relative implementation starts this way:
#implementation RootController
#synthesize tableView;
Now: I learnt that #synthesize is a sort of shortcut to avoid boring getters and setters.
But I've some question:
in the code of the implementation tableView is never explicitly called but the dealloc releases it;
if it never gets called explicitly why the #synthesize?
Is it mandatory for IBOutlets to be synthesized?
From Memory Management of Nib Objects,
When a nib file is loaded and outlets established, the nib-loading mechanism always uses accessor methods if they are present (on both Mac OS X and iOS). Therefore, whichever platform you develop for, you should typically declare outlets using the Objective-C declared properties feature.
For iOS, you should use:
#property (nonatomic, retain) IBOutlet UIUserInterfaceElementClass *anOutlet;
You should then either synthesize the corresponding accessor methods, or implement them according to the declaration, and (in iOS) release the corresponding variable in dealloc.
in the code of the implementation tableView is never explicitly called but the dealloc releases it;
That is because when you do assign a value to the tableView, your controller retains it, and it will need to release it when it gets dealloc'd. Don't forget, #properties declared in an interface are publicly accessible. In your case specifically, the tableView you're declaring as IBOutlet is initialized by the view controller loadView method using the connections you define in Interface Builder between the File's Owner and the UITableView.
if it never gets called explicitly why the #synthesize?
You need to provide accessors for all declared #properties. They can be #synthesized, or you could write your own.
Is it mandatory for IBOutlets to be synthesized?
No, but it's way more convenient that way. The rule enforced by the compiler is that #properties must have corresponding accessors (synthesized or not) in the implementation.
For reference: From Xcode 4.4 and LLVM Compiler 4.0 on the #synthesize directive is no longer required as it will be provided by default for #properties defined in the interface.
If you type
#property (nonatomic, retain) IBOutlet UITableView *tableView;
you tell the compiler: "Listen, there will be a getter and a setter. If appropriate, use them!" And it will use them when loading the nib.
Therefore you have to implement the getter and the setter otherwise the compiler will complain.
The IBoutlet pseudo-type is just a marker so that the InterfaceBuilder "knows" that the mentioned class-file has a handle/outlet to the UITableView instance.
When compiling IBOutlet is being removed by the preprocessor (InterfaceBuilder parses (looks at) the source files). It's similar with IBAction: it is being replaced with void by the preprocessor.
That said, you could use the reference to said instance to do stuff programmatically (Like adding/changing values of the UITableView)
Basically I want to be able to access the UIApplication delegate's window property all the way through my class, so I want to reference it with an iVar.
To this end I don't want to "own" it, just reference it.
So therefore should I just put a variable reference in the .h file?
#import <UIKit/UIKit.h>
#interface MessageView : UIView {
UILabel *messageLabel;
UIWindow *window;
}
#property (nonatomic, retain) UILabel *messageLabel;
#end
Or should I set the property there too?
I'm sceptical because the property would be nonatomic, retain, but I don't want to retain it, unless I actually do and I'm just being thick! :p
The purpose of having the window object is just to be able to add subviews to it, rather than the current view controller's view.
Thanks
Why not use
#property (nonatomic, assign) UIWindow *window
Then you are not retaining it.
Given the window should exist for the lifetime of your app there is no real need to retain it as it's already being retained by your app delegate.
Having a property in the first place in this scenario is nothing more than syntactic sugar
someclass.window = self.window; // Using a property
is much more succinct than
window = [UIApplication sharedApplication].window; // Using an iVar
Well you actually do want to retain the UIWindow. New projects by default retain it and there is nothing wrong with that. I see that MessageView is inheriting directly from UIView and that has a window property that is set once it is added to a window(or a subview of a window). Also look at willMoveToWindow: and didMoveToWindow. Now never think that you can not create a property just because you do not want to retain something because that is what the assign keyword is for.
#import <UIKit/UIKit.h>
#interface MessageView : UIView {
UILabel *messageLabel;
UIWindow *window;
}
#property (nonatomic, retain) UILabel *messageLabel;
#property (nonatomic, assign) UIWindow *window;
#end
Actually, no, you do not.
Whenever you use any of the UIWindow Make Key Window methods (as you probably is doing inside your AppDelegate), such as
– makeKeyAndVisible
– makeKeyWindow
The window becomes available from all your application just by using the UIApplication's keyWindow property.
[[UIApplication sharedApplication] keyWindow]
So, there is no need for a property or a retain in your AppDelegate or anywhere else, as it will be retained by your application class.
OBS: The property is commonly placed in your AppDelegate as the application template from XCode used the interface builder and an IBOutlet to instantiate the UIWindow. So, if your are creating your window by hand, there is no need for a property there.
What is the best way to pass an object between two views and how would I go about doing so?
If you are using two view controllers then making property will be best way for you.
in .h file
NSString *name;
#property (nonatomic, retain) NSString *name;
and in .m
#synthesize name;
for more how to use property look -
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW1
Use the properties declared in each controller.
I'm assuming you have two view controllers, ViewController1 and ViewController2. In both header files (.h), add an instance variable:
CustomObject *myObjectToPass;
and also
#property (nonatomic, retain) CustomObject *myObjectToPass;
If you are passing a BOOL, int or float, then do not retain it, for an NSString, use copy in place of retain, etc.
In the implementation file (.m), synthesize the variable:
#synthesize myObjectToPass;
Now you can get and set the object between viewControllers. The best way to do this depends on how they are related (e.g. in a navigationController or a tabBarContoller, etc). This should get you started, though.
Sometimes I see the following code into two different formats:
Format 1:
#import <UIKit/UIKit.h>
#interface MyViewController : UIViewController {
IBOutlet UILabel *myText;
}
#property (retain, nonatomic) UILabel *myText;
-(IBAction)buttonPressed:(id)sender;
#end
Format 2:
#import <UIKit/UIKit.h>
#interface MyViewController : UIViewController {
}
#property (retain, nonatomic) IBOutlet UILabel *myText;
-(IBAction)buttonPressed:(id)sender;
#end
which is the correct format? Why?
To clarify what Hack Saw said, and more directly answer your question, it does not matter whether you put IBOutlet in your property declaration or your instance variable declaration.
What Hack Saw was trying to say is that IBOutlet and IBAction both mean nothing to the compiler (IBAction gets compiled into void). The only reason they are there is for Interface Builder to parse the file and make a list of all objects and methods that you the developer says it should care about.
IBOutlet is a marker for interface builder to find your declarations, and make them available in the drop downs in IB.
They are strictly only required if you want to have IB connect an IB object to a reference in your code, for instance, connecting a button to a UIButton * declaration.
So, the basic idea here is that Interface Builder has a list of objects it knows how to make. You could make those objects in code, but a lot of the time, you don't need more capability than what IB offers, which is actually quite a lot.
In those cases, IB takes care of that object entirely. It allocates it, and sets the various parameters, and takes care of displaying it.
However, you obviously need to be able to talk to it, as well, most of the time. In order to do this, your declare a pointer to the object, like UIButton *mybutton, but in order to let IB know you want to connect up with it, you add IBOutlet to the declaration.
IB lists the variable, you connect the button up to something in File's Owner, or sometimes firstresponder, and then IB saves that connection data, and sets everything up when the nib gets loaded.
If I do this:
#interface RegisterController : UIViewController <UITextFieldDelegate>
{
IBOutlet UITextField *usernameField;
}
instead of this:
#interface RegisterController : UIViewController <UITextFieldDelegate>
{
UITextField *usernameField;
}
#property (nonatomic, retain) IBOutlet UITextField *usernameField;
Will something bad happen? I know in the second case, the field is retained, but does this make a different since the nib owns the field? Will the field go away without the retain? and under what circumstances? The code in the first case works, was wondering whether this is an issue or not in terms of memory management.
It is recommended you declare properties for all of your IBOutlets for clarity and consistency.
The details are spelled out in the Memory Management Programming Guide. The basic gist is, when your NIB objects are unarchived, the nib loading code will go through and set all of the IBOutlets using setValue:forKey:. When you declare the memory management behavior on the property, there is no mystery as to what is going on. If the view gets unloaded, but you used a property that was declared as retain, you've still got a valid reference to your textfield.
Perhaps a more concrete example would be useful to indicate why you should use a retaining property:
I'm going to make some assumptions about the context in which you're working--I'll assume the UITextField above is a subview of another view that is controlled by a UIViewController. I will assume that at some point, the the view is off the screen (perhaps it is used in the context of a UINavigationController), and that at some point your application gets a memory warning.
So lets say your UIViewController subclass needs to access its view to display it on screen.
At this point, the nib file will be loaded and each IBOutlet properties will be set by the nib loading code using setValue:forKey:. The important ones to note here are the top level view that will be set to the UIViewController's view property, (which will retain this top level view) and your UITextField, which will also be retained. If it is simply set, it'll have a retain put on it by the nib loading code, otherwise the property will have retained it. The UITextField will also be a subview of the top level UIView, so it will have an additional retain on it, being in the subviews array of the top level view, so at this point the text field has been retained twice.
At this point if you wanted to switch out the text field programmatically, you could do so. Using the property makes memory management more clear here; you just set the property with a new autoreleased text field. If you had not used the property, you must remember to release it, and optionally retain the new one. At this point it is somewhat ambiguous as to whom owns this new text field, because the memory management semantics are not contained within the setter.
Now let's say a different view controller is pushed on the UINavigation Controller's stack, so that this view is no longer in the foreground. In the case of a memory warning, the view of this offscreen view controller will be unloaded. At this point, the view property of the top level UIView will be nulled out, it will be released and deallocated.
Because the UITextField was set as a property that was retained, the UITextField is not deallocated, as it would have been had its only retain been that of the subviews array of the top level view.
If instead the instance variable for the UITextField not been set via a property, it'd also be around, because the nib loading code had retained it when setting the instance variable.
One interesting point this highlights is that because the UITextField is additionally retained through the property, you'll likely not want to keep it around in case of a memory warning. For this reason you should nil-out the property in the -[UIViewController viewDidUnload] method. This will get rid of the final release on the UITextField and deallocate it as intended. If using the property, you must remember to release it explicitly. While these two actions are functionally equivalent, the intent is different.
If instead of swapping out the text field, you chose to remove it from the view, you might have already removed it from the view hierarchy and set the property to nil, or released the text field. While it is possible to write a correct program in this case, its easy to make the error of over-releasing the text field in the viewDidUnload method. Over-releasing an object is a crash-inducing error; setting a property that is already nil again to nil is not.
My description may have been overly verbose, but I didn't want to leave out any details in the scenario. Simply following the guidelines will help avoid problems as you encounter more complex situations.
It is additionally worth noting that the memory management behavior differs on Mac OS X on the desktop. On the desktop, setting an IBOutlet without a setter does not retain the instance variable; but again uses the setter if available.
Declaring something IBOutlet, from a memory management standpoint, does nothing (IBOutlet is literally #defined as nothing). The only reason to include IBOutlet in the declaration is if you intend to connect it in Interface Builder (that's what the IBOutlet declaration is for, a hint to IB).
Now, the only reason to make an #property for an instance variable is if you intend to assign them programatically. If you don't (that is, you're only setting up your UI in IB), it doesn't matter whether you make a property or not. No reason to, IMO.
Back to your question. If you're only setting this ivar (usernameField) up in IB, don't bother with the property, it won't affect anything. If you DO make a property for usernameField (because you're programatically creating it), definitely do make a property for it, and absolutely DO make the property retain if so.
In fact there are two models:
THE OLD MODEL
These model was the model before Objective-C 2.0 and inherited from Mac OS X. It still works, but you should not declare properties to modify the ivars. That is:
#interface StrokeWidthController : UIViewController {
IBOutlet UISlider* slider;
IBOutlet UILabel* label;
IBOutlet StrokeDemoView* strokeDemoView;
CGFloat strokeWidth;
}
#property (assign, nonatomic) CGFloat strokeWidth;
- (IBAction)takeIntValueFrom:(id)sender;
#end
In this model you do not retain IBOutlet ivars, but you have to release them. That is:
- (void)dealloc {
[slider release];
[label release];
[strokeDemoView release];
[super dealloc];
}
THE NEW MODEL
You have to declare properties for the IBOutlet variables:
#interface StrokeWidthController : UIViewController {
IBOutlet UISlider* slider;
IBOutlet UILabel* label;
IBOutlet StrokeDemoView* strokeDemoView;
CGFloat strokeWidth;
}
#property (retain, nonatomic) UISlider* slider;
#property (retain, nonatomic) UILabel* label;
#property (retain, nonatomic) StrokeDemoView* strokeDemoView;
#property (assign, nonatomic) CGFloat strokeWidth;
- (IBAction)takeIntValueFrom:(id)sender;
#end
In addition you have to release the variables in dealloc:
- (void)dealloc {
self.slider = nil;
self.label = nil;
self.strokeDemoView = nil;
[super dealloc];
}
Furthermode, in non-fragile platforms you can remove the ivars:
#interface StrokeWidthController : UIViewController {
CGFloat strokeWidth;
}
#property (retain, nonatomic) IBOutlet UISlider* slider;
#property (retain, nonatomic) IBOutlet UILabel* label;
#property (retain, nonatomic) IBOutlet StrokeDemoView* strokeDemoView;
#property (assign, nonatomic) CGFloat strokeWidth;
- (IBAction)takeIntValueFrom:(id)sender;
#end
THE WEIRD THING
In both cases, the outlets are setted by calling setValue:forKey:. The runtime internally (in particular _decodeObjectBinary) checks if the setter method exists. If it does not exist (only the ivar exists), it sends an extra retain to the ivar. For this reason, you should not retain the IBOutlet if there is no setter method.
There isn't any difference between the way those two interface definitions work until you start using the accessors provided by the property.
In both cases, you'll still need to release and set-to-nil the IBOutlet in your dealloc or viewDidUnload methods.
The IBOutlet points to an object instantiated within a XIB file. That object is owned by the File's Owner object of the XIB file (usually the view controller that the IBOutlet is declared in.
Because the object is created as a result of loading the XIB, it's retain count is 1 and is owned by your File's Owner, as mentioned above. This means that the File's Owner is responsible for releasing it when it's deallocated.
Adding the property declaration with the retain attribute simply specifies that the setter method should retain the object passed in to be set - which is the correct way to do it. If you did not specify retain in the property declaration, the IBOutlet could possibly point to an object that may not exist any more, due to it being released by its owner, or autoreleased at some point in the program's lifecycle. Retaining it prevents that object being deallocated until you're done with it.
Objects in the nib file are created with a retain count of 1 and then autoreleased. As it rebuilds the object
hierarchy, UIKit reestablishes connections between the objects using setValue:forKey:, which uses the
available setter method or retains the object by default if no setter method is available. This means that any object for which you have an outlet remains valid. If there are any top-level objects you do not store in outlets, however, you must retain either the array returned by the loadNibNamed:owner:options: method or the objects inside the array to prevent those objects from being released prematurely.
Well, in the second case you're adding a getter/setter method for that particular IBOutlet. Any time you add a getter/setter method you (almost always) want to have it set to retain for memory management issues. I think a better way to have posed you're question would have been this:
#interface RegisterController : UIViewController <UITextFieldDelegate>
{
IBOutlet UITextField *usernameField;
}
#property (nonatomic) IBOutlet UITextField *usernameField;
or
#interface RegisterController : UIViewController <UITextFieldDelegate>
{
IBOutlet UITextField *usernameField;
}
#property (nonatomic, retain) IBOutlet UITextField *usernameField;
In that case, then yes, you would need to add a retain since it will affect memory management. Even though it may not have any effects, if you're programatically adding and removing IBOutlet's, you could potentially run into issues.
As a general rule: always add an #property (with retain) whenever you have an IBOutlet.