公共私人和保护在objective-c

问题描述:

嗨我想学习目标C中的Opps概念,但我知道PHP,所以我采取了公共,私人和保护提到的波纹管程序。公共私人和保护在objective-c

<?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 

?> 

因此,我试图在下面提到的Objective C代码中进行转换。

#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; 
} 

当我运行上面的代码我得到

2015-11-03 23:20:16.877 Access Specifier[3562:303] 0 

有人能解决我的问题。

+0

你正在编译iOS或OS X吗? –

+0

我正在编译OS X命令行工具。只是想知道公共私人和受保护的概念。 – VyTcdc

这种类型的问题之前,已要求并有在接受答案的Private ivar in @interface or @implementation

一般一个很好的解释,我会建议你避免实例变量和使用@property代替。属性具有只读/写入控制的优点,以及免费的合成设置器和获取器(如果您正在学习OOP概念是您应该采用的关键概念)。

属性在Obj-C文件的@interface部分中声明。对于访问控制(根据链接),您没有公共/私人/受保护的关键字。如果在.h文件中定义的所有Obj-C方法(以及扩展属性)都是公共的。如果你想让他们“私人”,你可以在.m文件中使用类别类别定义它们:

//MyClass.m 
@interface MyClass() 
@property(nonatomic, retain) NSString* myString; 
@end 

@implementation MyClass 
@end 
+0

首先感谢您对我的查询的回复,好吧,我想要得到的输出值是30,但我在该编码中得到0,您能否告诉我该怎么做。 – VyTcdc

+0

如果您将您的ivars转换为属性,则它们具有默认值。 'int'默认为0,所以你需要在你的类被分配和初始化之后覆盖你的'init'构造函数来设置这些值。 Obj-C自定义/覆盖init的堆栈溢出搜索,或者参考最近的Obj-C书籍或学习网站的细微差别,因为Obj-C的构造函数实现与PHP的不同。 –

+0

如果您还有其他人在StackOverflow上没有询问过的问题,请随时发起一个新问题。 –