Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way for defining Property in iPhone

Tags:

iphone

Hi what is the difference between a)

@interface SViewController : UITableViewController{

NSString *_name;

}

@property (nonatomic, retain) NSString *name;


@synthesize name = _name;

b)

@interface SViewController : UITableViewController{

NSString *name;

}

@property (nonatomic, retain) NSString *name;

@synthesize name;
like image 592
iPhoneDev Avatar asked Nov 28 '25 15:11

iPhoneDev


2 Answers

Skip the ivar and just have the property declaration. If you need private members and methods, use a class extension.

An example:

@interface MyObject : NSObject {
}

@property (nonatomic,retain) NSString *publicString;

-(void)publicMethod;

@end

and implemention:

#import "MyObject.h"

@interface MyObject ()
@property (nonatomic,retain) NSString *internalString;
-(void)internalMethod;
@end

@implementation MyObject

@synthesize publicString;
@synthesize internalString;

-(void)publicMethod {}
-(void)internalMethod {}

@end

Note: One downside not declaring an ivar and just have the property, is that gdb in Xcode4 (<= 4.0.1) won't show the property when debugging. Very annoying when writing iOS code, as you can't use LLDB for debugging iOS projects yet.

like image 195
Erik Tjernlund Avatar answered Dec 02 '25 04:12

Erik Tjernlund


I prefer a) option, as it prevents you from accidentally forgetting to release or over-release resources. You just always access your variable as self.name and assign either nil or autoreleased value (in case it's a retain property as in your example). In this case if you try to assign a value to "name" without "self." you'll get an error.

like image 40
Alex Staravoitau Avatar answered Dec 02 '25 03:12

Alex Staravoitau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!