- What is a Property?
- Why is it used?
- How to declare a property in Objective C?
@interface Myclass : NSObject
{
int num1, num2; //global variables of integer type
}
@property (readwrite,assign) int num1, num2; //set the property for those integer variable
//you use assign in a case where you cannot retain the value like BOOL or NSRect, else use retain
//If you use retain then you become the owner of that particular property and you must release that property once its use is over.
-(void)add; //add function
@end
@implementation Myclass
@synthesize num1, num2; //synthesize will automatically set getter and setter for your property
-(void)add
{
int result= num1+num2;
NSLog(@"Result of addition is %d",result);
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Myclass *obj_Myclass = [[Myclass alloc]init];
[pool addObject:obj_Myclass]; //adding object to the pool
obj_Myclass.num1 = 10; //invoking setter method
obj_Myclass.num2 = 20; //invoking setter method
[obj_Myclass add]; //calling the add method
[pool drain];
return 0;
}
@property (readonly,assign) int num1, num2;
You can change the value directly by referencing it directly, refer the code below
-(void)add
{
self->num1 = 10; //legal
self->num2 =20; //legal
int result= num1+num2;
NSLog(@"Result of addition is %d",result);
}
Ravi,
ReplyDeleteI really appreciate the efforts that you are putting in here.. This is cool and equally benevolent. Keep rocking !!!
thanks its good basics you describe.
ReplyDelete