公共私人和受保护的目标c

时间:2015-11-03 18:17:00

标签: ios iphone ipad ios7 ios5

您好我正在尝试在Objective C中学习Opps概念,但我知道PHP所以我参加了一个程序,其中包括公开,私有和受保护的提及。

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

有人可以解决我的问题。

1 个答案:

答案 0 :(得分:1)

之前已经提出过这类问题,并且在Private ivar in @interface or @implementation

的已接受答案中有一个很好的解释

一般情况下,我建议您避免使用实例变量,而是使用@property。属性具有只读/写入控件以及自由合成的setter和getter(如果您正在学习OOP概念,那么这是您应该使用的一个关键概念)。

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

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

@implementation MyClass
@end
相关问题