Reputation: 986
Hi I am trying to learn Opps concept in Objective C but I know PHP so I took a program in which for public, private and protected mentioned bellow.
<?php
//Public properties and method can be inherited and can be accessed outside the class.
//private properties and method can not be inherited and can not be accessed outside the class.
//protected properties and method can be inherited but can not be accessed outside the class.
class one
{
var $a=20;
private $b=30;
protected $c=40;
}
class two extends one
{
function disp()
{
print $this->c;
echo "<br>";
}
}
$obj2=new two;
$obj2->disp(); //Inheritance
echo"<br>";
$obj1=new one;
print $obj1->c; //Outside the class
?>
So this I am trying to convert in Objective c code mentioned bellow.
#import <Foundation/Foundation.h>
@interface one : NSObject
{
@private int a;
@public int b;
@protected int c;
}
@property int a;
@property int b;
@property int c;
@end
@implementation one
@synthesize a,b,c;
int a=10;
int b=20;
int c=30;
@end
@interface two : one
-(void)setlocation;
@end
@implementation two
-(void)setlocation;
{
// NSLog(@"%d",a);
NSLog(@"%d",b);
// NSLog(@"%d",c);
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
two *newtwo;
newtwo =[[two alloc]init];
//calling function
[newtwo setlocation];
}
return 0;
}
When I run the above code I am getting
2015-11-03 23:20:16.877 Access Specifier[3562:303] 0
Can some one resolve my problem.
Upvotes: 1
Views: 2642
Reputation: 346
This type of question has been asked before and there's a good explanation in the accepted answer for Private ivar in @interface or @implementation
In general I would recommend you avoid instance variables and use @property
instead. Properties have the benefit of read-only/write controls, and free synthesized setters and getters (which if you're learning OOP concepts is a critical concept you should employ).
Properties are declared in the @interface
part of an Obj-C file. For access control (according to the link) you have no public/private/protected keywords. All Obj-C methods (and by extension, properties) are public if they're defined in the .h file. If you want them "private" you define them in the the .m file using a class category:
//MyClass.m
@interface MyClass ()
@property(nonatomic, retain) NSString* myString;
@end
@implementation MyClass
@end
Upvotes: 1