Property with no iVar and getter method? - iphone

I spotted this today and just want to verify my understanding of what is going on. "prefixName" is a readonly property that uses a getter method to directly pass a value back, there is no iVar storing the result on the PR_ViewController object. Also if the property was not readonly adding a setter still would not work as there is no iVar to set.
Created: [Meth] prefixName
By contrast "characterName" works the usual way for a property, adding a getter, a setter and an iVar.
Created: [Meth] characterName
Created: [Meth] setCharacterName
Created: [iVar] characterName
.
#interface PR_ViewController : UIViewController
#property (nonatomic, readonly) NSString *prefixName;
#property (nonatomic, retain) NSString *characterName;
.
#implementation PR_ViewController
#synthesize characterName;
- (NSString *)prefixName {
return #"FRED";
}

You are not required to synthesize accessors - you can perfectly well write them yourself, which is what is done in your example.
Further, a read-only property does not have to be based on an ivar, but can be computed, based on other ivars or properties. This can be useful if you use bindings to display values in the UI that are derived from other properties, provided you like that coding style.
Here is a simple example of a readonly property computed based on two other properties:
Header file:
#property double width;
#property double height;
#property (readonly) double area;
Implementation:
#synthesize width, height;
- (double)area
{
return width*height;
}
+ (NSSet *)keyPathsForValuesAffectingArea
{
return [NSSet setWithObjects:#"width", #"height", nil];
}
Now, whenever either one of width or height changes, the area property changes, too, and its changes are propagated to its listeners (thanks to keyPathsForValuesAffectingArea.)
You can also see the fullName example in this doc.

Related

clarifying on properties in objective C

Sorry for the simple question.
When I see a definition of a property inside the h file, but outside of the class #interface scope, what does it mean ?
#property (nonatomic, readonly) RMMapContents *mapContents;
Here is the code:
#class RootViewController;
#class RMMapContents;
#interface MapTestbedAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
//MAIN VIEW
//==============
RootViewController *rootViewController;
// NETWORK DATA
// =============
NSMutableArray *photoTitles; // Titles of images
NSMutableArray *photoSmallImageData; // Image data (thumbnail)
NSMutableArray *photoURLsLargeImage; // URL to larger image
NSMutableData *receivedData;
NSURLConnection *theConnection;
NSURLRequest *request;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet RootViewController *rootViewController;
#property (nonatomic, readonly) RMMapContents *mapContents;
#end
Inside a function I see this line:
- (void)foo:(xyz *)abc{
..
RMMapContents *mapContents = [self mapContents];
..
}
So, taking it from C++, the mapContents seem like it is not a global scope var (after all, that's why they call them properties, right?), but isn't defining the same name again inside the function weird a bit?
I hope someone can clarify a little here.
Thanks!
The scope of the #interface block extends upto the #end keyword and is not restricted to the braces {}.
So the #property declaration lies very much inside the scope of the #interface and like cli_hlt rightly answered, it acts like a substitute to setter and getter methods for the mapContents property.
so a property named mapContents, would have setters and getters which look like this :
- (void)setMapContents; //setter
- (RMMapContents *)mapContents; //getter
and would can be accessed from within the class using these methods:
[self setMapContents:newContents];
AND
RMMapContents *contents = [self mapContents];
Well, a property is not just a variable. A property is a variable plus its setter and getter methods. A property is usually said to be backed by a variable, which usually(but not always) has the same name as the property itself.
So there are basically three scenarios:
The developer has redefined the backing variable, look for something like:#synthesize mapContents=mapContents_, at the beginning of the implementation -> no problem here.
The compiler defined the variable to be something you don't now but not equal to mapContents - > no problem.
The property backing variable is indeed called "mapContents", so then the local definition hides the global definition (look for a compiler warning here). But by calling [self mapContents] you will not access the global variable but call the getter, which in turn will access the class variable (because then the local mapContents is out of scope)
Hope this helps.
global var mapContents is readonly,in foo function , create a new pointer,then you can change the value of inner var.
Look for a method in your class with a name mapContents that will return a initialization to your RMMapContents class.
Basically this line RMMapContents *mapContents = [self mapContents]; says that initializing an instance of RMMapContents called mapContens using the method mapContents.

General Programming Question about properties, assign, retain, and declarations

I was going through the AVCam project from WWDC and I'm curious about the following code. I thought you were supposed to declare an object, then #property (nonatomic,retain), then synthesize.
The Demo code does it a little differently, I'll post some code (just a sample), anyone know what this does and when you should use it? Can anyone explain its significance and when to use it?
#interface AVCamCaptureManager : NSObject {
#private
// Capture Session
AVCaptureSession *_session;
AVCaptureVideoOrientation _orientation;
// Identifiers for connect/disconnect notifications
id _deviceConnectedObserver;
id _deviceDisconnectedObserver;
}
#property (nonatomic,readonly,retain) AVCaptureSession *session;
#property (nonatomic,assign) AVCaptureVideoOrientation orientation;
#property (nonatomic,readonly,retain) AVCaptureAudioChannel *audioChannel;
#property (nonatomic,assign) NSString *sessionPreset;
in the implementation file:
#interface AVCamCaptureManager ()
#property (nonatomic,retain) AVCaptureSession *session;
#property (nonatomic,retain) AVCaptureDeviceInput *videoInput;
#property (nonatomic,retain) AVCaptureDeviceInput *audioInput;
#end
#implementation AVCamCaptureManager
#synthesize session = _session;
#synthesize orientation = _orientation;
#dynamic audioChannel;
#dynamic sessionPreset;
#dynamic focusMode;
- (id) init
{
#property (nonatomic,readonly,retain) AVCaptureSession *session;
This is a property that is readonly externally. Internally, it will have a setter that retains the new value.
#property (nonatomic,assign) AVCaptureVideoOrientation orientation;
This is a property that does a simple assignment to store the new value (since you can't -copy or -retain primitives).
#property (nonatomic,readonly,retain) AVCaptureAudioChannel *audioChannel;
This is a property that is readonly externally. Internally, it will have a setter that retains the new value.
#property (nonatomic,assign) NSString *sessionPreset;
This is a property that does a simple assignment to store the new string value. This is normally not a good idea, unless you're only allowing pre-defined constants for the presets. When dealing with NSString properties, you generally want them to be copy unless you have a good reason against it.
In the implementation file:
#property (nonatomic,retain) AVCaptureSession *session;
#property (nonatomic,retain) AVCaptureDeviceInput *videoInput;
#property (nonatomic,retain) AVCaptureDeviceInput *audioInput;
These are used in conjunction with the properties declared in the header, except now it's readwrite. By declaring the version in the header as readonly, anyone using the class will not have access to the setSession: method. We re-declare this property internally so that we can have access to the setter (and the setter retains the new value). Also, if the property is not present in the header, the user won't know it exists, but we'll still be able to use it internally.
#synthesize session = _session;
#synthesize orientation = _orientation;
This means you want the compiler to generate the appropriate setters and getters for the session and orientation properties, and that you want those properties to store their values in the _session and _orientation instance variables, respectively.
#dynamic audioChannel;
#dynamic sessionPreset;
#dynamic focusMode;
This means that the implementations for the setters and getters will be provided at runtime. You usually don't use #dynamic properties yourself, other than the ones provided by the Core Data framework.
In this code, the session property is defined as readonly outside of the class and readwrite inside the class. By overriding the session property in an unnamed category before synthesizing it, a set accessor will also be synthesized, but the header file says it is readonly so other classes don't know about the set accessor. The category also defines two new properties which are not visible to other classes at all.
The retain and assign keywords tell the compiler how the accessor methods should work. Retain means that the set accessor should retain the value of the property, and the assign keyword tells it to set the property without retaining it. There is also copy, which copies the value and is often used to make sure a mutable value isn't set. The default is assign, but the compiler will issue a warning if nothing is specified for an object property.
Can you explain what you're confused about here? My only guess is you are confused about audioChannel and sessionPreset, as they have no ivars and are declared #dynamic (there's also focusMode, but I don't even see a #property declaration for that in the code you pasted).
In any case, I expect that if you read the rest of the code you'll find that there are getters for -audioChannel and -sessionPreset that have been written, as well as a setter for -setSessionPreset:. Assuming that's the case, then the #dynamic declarations are completely unnecessary. #dynamic is only necessary to tell the compiler that the methods will exist at run-time; if they exist at compile-time then you don't need any directive whatsoever.

When would a instance variable be used and when would a property be used?

In a header file such as this, when would an instance variable be used and when would a property be used?
Do they have to have the same name?
#import <UIKit/UIKit.h>
#class BlueViewController;
#class YellowViewController;
#interface SwitchViewController : UIViewController {
YellowViewController *yellowViewController;
BlueViewController *blueViewController;
}
#property (retain, nonatomic) YellowViewController *yellowViewController;
#property (retain, nonatomic) BlueViewController *blueViewController;
#end
A #property declaration simply creates accessor methods for an ivar. So properties don't really have names, only the accessor methods do; and these don't have to have the same name as the ivar. In fact, they don't even have to have a corresponding ivar.
You can change the names of the methods using the getter and setter decorators like this:
#property (assign, getter=isValid) BOOL valid;
Now, as I said, a #property declaration simply creates accessor methods for an ivar. So you use properties when you want accessor methods. Here are a few reasons why you might want accessor methods:
Encapsulation (a property might be advertised as a different type than the ivar, or might not even have an ivar)
Related state changes (change another ivar or invoke a method when an ivar is modified)
You can use the retain decorator and #synthesize the property to get much simpler memory management
You can use atomic decorator (or simply not use the nonatomic decorator, since properties are atomic by default) to create atomic properties
Here's an example to demonstrate points 1 and 2:
#interface Foo : NSObject {
#private
int flags;
// Humpty and Dumpty are mutually exclusive
BOOL humpty;
BOOL dumpty;
}
#property (nonatomic) BOOL flagA;
#property (nonatomic) BOOL flagB;
#property (nonatomic) BOOL humpty;
#property (nonatomic) BOOL dumpty;
#property (nonatomic, readonly, getter=isClean) BOOL clean;
#end
#implementation Foo
#synthesize humpty, dumpty; // Synthesize the getters, but provide the setters
- (void)setHumpty:(BOOL)value {
if(value && dumpty)
dumpty = NO;
humpty = value;
}
- (void)setDumpty:(BOOL)value {
if(value && humpty)
humpty = NO;
dumpty = value;
}
- (BOOL)flagA {
return flags & 0x01;
}
- (void)setFlagA:(BOOL)value {
if(value)
flags |= 0x01;
else
flags &= ~0x01;
}
- (BOOL)flagB {
return flags & 0x02;
}
- (void)setFlagB:(BOOL)value {
if(value)
flags |= 0x02;
else
flags &= ~0x02;
}
// Making this a property doesn't really make sense
// but I'm just trying to demonstrate what you can do
// with properties
- (BOOL)isClean {
return flags == 0;
}
#end
You want to use the properties for all your external access to provide encapsulation, it's up to you whether you want to use them internally though, i think it's a matter of taste.
By using the properties from outside of your class you can for example do some lazy loading and it becomes a lot easier to make any potential API changes by providing deprecation warnings in the getters/setters.
They can have the same name, although they don't have to. Indeed, it's not required for the externally-visible property to correspond exactly to a single instance variable at all. Such a correspondence is expected if you're going to #synthesize the accessor methods, but there are quite legitimate reasons for creating the methods manually and making them do something other than just getting/setting a matching ivar.
Instance variables are normally not accessible from the outside world, so all external access has to be via the property methods. (It is possible to declare ivars #public, but this is rarely a good idea.)
From within the object, whether you access as properties or instance variables depends on what the properties actually are and what you're doing with them.
For simple synthesized properties it is common to use the accessors (either explicitly using [self setXxx] or using the dot notation as self.xxx) except within dealloc (and possibly init, depending on who you ask).
In more complex cases, you really have to think about what it is you are trying to achieve. But if you've gone to the trouble of making them properties you probably want whatever functionality is encapsulated in the accessor methods to be called most of the time.
At any rate, read the properties documentation to get a better understanding of what's going on.

Is it necessory to define property for an IBOutlet field?

I have seen many iPhone examples to use IBOutlet as a field linked to a UI control in Interface Builder, and the field is also defined as property in the interface class. For example, the following codes are similar ones from Apple example codes:
// in .h file
#interface MyViewController : UIViewController {
IBOutlet UILabel* _firstName;
IBOutlet UILabel* _lastName;
...
}
#property (nonatomic, retain) UILabel* firstName;
#property (nonatomic, retain) UILabel* lastName;
...
#end
// in .m file
#implementation MyViewController {
#synthetic firstName = _firstName;
#synthetic lastName = _lastName;
...
#end
I tried to link labels in Interface Builder to my controller class IBOutlets and I can see _firstName and _lastName. Since the linkage is directly from Interface Builder to my interface class members (even private ones if I place #private directive). Do I need to define properties for those fields?
Actually, I tried to remove these properties and it seems my codes work fine. By defining properties, my class expose them as public. I don't have any usage or reason for them as properties within or out side my codes. My question is that if this practice, defining fields as properties, necessary? Do I miss any thing such as memory management which might be called from Objective-C concept or framework?
As Jeremie Wekdin mentioned that, my question is somehow duplicated. The similar question and answers do reveal that in case of nib/xib file being used, there is memory issue to be considered.
In short, Cocoa will look for setOutletName first, and use the property method to set UI control object; otherwise, Cocoa will direct set to the class member variable and retain it. That means the filed object should be released in dealloc method.
That's fine. However, in case of my question, my field variable has different name from its corresponding property name, like _firstName and firstName. In this case, I think that Cocoa is not smart enough to figure out the property method and object retrieved from nib/xib is directly set to the class member.
To verify it, I overwrite the setter:
// in .m file
#implementation MyViewController {
#synthetic firstName = _firstName;
- (void) setFirstName:(UILabel*) value {
NSLog("_firstname: %#", _firstName);
[_firstname autorelease];
_firstName = [value retain];
}
Then I load my view, the log message does not show in the XCode's output console. However, if I keep the variable name and property name the same. I do see the setter is called:
// in .h
#interface MyViewController : UIViewController {
IBOutlet UILabel* firstName;
...
}
#property (nonatomic, retain) UILabel* firstName;
...
#end
// in .m file
#implementation MyViewController {
#synthetic firstName;
- (void) setFirstName:(UILabel*) value {
NSLog("firstName: %#", firstName);
[firstName autorelease];
firstName = [value retain];
}
...
#end
In the output console, when the view shows, I see:
firstName: (null)
As the duplicated QA suggested, I read the Appl's Resource Programming Guide. Find the document in the section The Nib Object Life Cycle, The Object Loading Process, and #3 Outlet connection. You should see that Mac OS X and iPhone OS have different ways to connect outlet to objects. "In iPhone OS, the nib-loading code uses the setValue:forKey: method to reconnect each outlet"
So I tried the following codes:
#implementation MyViewController {
#synthetic firstName = _firstName;
- (void) setValue:(id) value forKey:(NSString*) key {
NSLog("forKey: %#; value: %#", key, value);
if ([key isEqualToString:#"_firstName"])
// It should then call the accessor or property
// self._firstName = value;
// to set value, like the follow codes in the setter:
[_firstName autorelease];
_firstName = [value retain];
}
...
}
...
#end
I recompiled my code again and I did see all the property setter calls, including the key _firstName. Continued from Apple's doc:
"That method (setValue:forKey:) similarly looks for an appropriate accessor method and falls back on other means when that fails."
This explains why in my case(property name is different from outlet variable name) the property is called by Cocoa.
In conclusion, there is a memory issue when IBOutlet and nib/xib are used (as a way to load views) for a field control. It would be nice to let Cocoa to find out a defined accessor or property to set a field variable, which handles retaining objects. If you define a property for an IBOutlet field variable, both should have the same. As a result, the codes will work in both Mac OS X and iPhone OS.

#property #synthesize

What do #synthesize and #property do in Xcode? Please provide an explanation in really simple terms?
You asked for simple terms:
#property declares a property in your
class header
#property (nonatomic, retain) NSString *myString;
#synthesize creates your setter and
getter for your property (accessor
methods)
Without synthesize you have to write
your own setter and getter
implemention, like getMyString or
setMyString (capitalize the first
character of your property)
Sam: Just an advice: http://www.cocoadevcentral.com/d/learn_objectivec/ is a pretty solid resource to learn about basics like properties.
Good Luck!
Properties and synthesized accessors are new features in Objective-C 2.0.
When you declare a #property you declare somewhat an instance var. Then you #synthesize accessor methods (i.e. getter and setter) for that property.
There are also #dynamic accessors if you're interested.
You should really do your homework on this. Apple has nifty pdf for that.
Think of all objective-c magic as just a "smarter macro", like a "smarter #define statement"
#property if you notice is always in the h file,
#synthesize is always in the m file.
So in the background
#property (whatever) NSString *myString;
becomes a declaration of 2 methods and a private variable;
void set_myString:(NSString *) str;
(NSString*) get_myString;
declarations in the header file
to make them do something their implementation is added into m file when you type in
#synthesize myString;
which becomes something like
void set_myString:(NSString *)str
{
myString = str;
}
(NSString *) get_myString
{
return (myString);
}
But it's smarter than this
depending on if you say "retain" "strong" or "weak"
it will either just return the pointer to the myString or it will copy the myString into a new object
So all of this is done automatically by a compiler just by reading your declarations.
Which is quite useful and saves a lot of time
By default all our variables are Private so we can't acess out of the class.
if we want to use our instance variable in out of the class.
When you declare a #property you declare somewhat an instance var. Then you #synthesize accessor methods (i.e. getter and setter) for that property.
There are also #dynamic accessors if you're interested.
it simply sets the property's setter variable name in it's own class.
For example lets say I have this: #property (nonatomic, copy) NSArray* viewControllers;
Well if i want to access the setter _viewController i wouldn't set a synthesize variable.
but if i want to access the viewController variable by the name viewController instead of _viewController, I would do #synthesize viewController;.
If I wanted to use it as a completely different name I could do this #synthesize viewControllers = viewControlololer; but that's only setter. As you will notice [self viewControllers] only works and not [self viewControlololer];
So I don't understant why everyone writes sets the "setter and getter" of a property. It doesn't change the getter variable at all... unless that means [self viewController] is aware of viewControlololer (obviously).
Actually properties are synthesized, either implicitly or explicitly. Properties are implicitly synthesized. So there's no need to use synthesized unless you wanna change the name of the variable to something different than _property_name.
There are other use cases, for example if you don't want an instance variable to back your property.
Properties are explicitly synthesized by using the #synthesized directive.
(Answer extracted from the Big Nerd Ranch guide)