[英]public private and protected in objective-c
嗨,我正在嘗試學習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
有人可以解決我的問題嗎?
之前已經問過這種類型的問題,並且@interface或@implementation中的Private ivar的可接受答案有很好的解釋。
通常,我建議您避免使用實例變量,而應使用@property
。 屬性具有只讀/寫入控件以及免費的綜合setter和getter的優點(如果您正在學習OOP概念,則應該使用它是一個關鍵概念)。
屬性在Obj-C文件的@interface
部分中聲明。 對於訪問控制(根據鏈接),您沒有公共/私有/受保護的關鍵字。 如果在.h文件中定義了所有Obj-C方法(以及擴展名,屬性),則它們是公共的。 如果希望它們“私有”,則可以使用類類別在.m文件中定義它們:
//MyClass.m
@interface MyClass ()
@property(nonatomic, retain) NSString* myString;
@end
@implementation MyClass
@end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.