I am new to iOS so take me slow. When i declare an object in my .h view controller named "_a" and i declare a property "a" and when i synthesize in the .m file
@synthesize a=_a;
must i use "a" or "_a" when i modify that object ? ( "a" is a UINavigationController in my case).
In another question开发者_C百科, does my compiler automatically draw a connection from a object declared "ob" to a "_ob" declaration ?
Again, sorry for the poor explanation but this environment isn't quite something i am use to.
An object declared like this:
@interface Example : NSObject {
NSObject *_a;
}
@property (retain) NSObject *a;
@end
And implemented like this:
#import "Example.h"
@implementation Example
@synthesize a = _a;
@end
Makes an ivar named _a
and two accessor methods in the Example
object. The accessor methods have these signatures:
- (NSObject *)a;
- (void)setA:(NSObject *)theA;
Method a
returns the object in the _a
ivar. Method setA
releases the object stored in _a
(if not nil), assigns the parameter to _a
, and sends the parameter an retain
message.
These methods may also be access through dot notation:
Example *e = [[Example alloc] init];
// These two are equivalent.
e.a = anotherNSObject;
[e setA:anotherNSObject];
// These two are equivalent.
anotherNSObject = e.a;
anotherNSObject = [e a];
Accessing _a
directly will circumvent the accessor methods, potentially causing problems such as memory leaks. For example if _a
holds the only reference to an object and a new object reference is assigned to _a
the old object will become a leaked object.
To directly answer your two questions:
You may use either a
or _a
. In most cases you'll be better off using _a
when reading the value within methods of the object declaring a
, and setA
(or a
in dot notation) when setting the value of _a
. Objects that use Example
objects should use the accessor methods (with or without dot notation).
The complier does not automatically make a connection between ob
and _ob
declarations. In this example the @synthesize a = _a;
statement makes the connection with the optional = _a
. The ivar may have any name. @synthesize a = george;
would also be valid. Without the = _a
part the compiler would make an ivar named a
and two accessor methods.
One further note: You may omit the declaration of _a
in the interface, which restricts the scope of the _a
ivar to just the implementation of the Example object. Adding the optional = _a
to the @synthesize
statement will make as ivar of the same type as the property declared in the interface.
@synthesize tell to compiler to generate setter and getter methods for your property. You can use _a as ivar or self.a as property, there are no difference. Also you can set your class variable from another class via this property
[myClassInstance setA:newA];
oldA = [myClassInstance a]; //oldA = myClassInstance.a
精彩评论