我有關於類方法曝光的學術問題。有一些我顯然不明白這一點,希望得到知情人士的澄清。類方法曝光和屬性定義
背景: 我有兩個名爲ViewController和ClassB的類的簡單示例。類B包含一個名爲returnArray的方法。 ViewController訪問數組的數據。我已經暴露了ClassB.h文件中的returnArray方法。
問題: 爲什麼我可以在ViewController中訪問數組的數據而無需定義屬性?我認爲這個屬性會創建一個getter來允許訪問數組。我的例子(只暴露方法)允許我在不創建@property的情況下訪問數據。
類方法:
ClassB.h
@interface ClassB : UIViewController
+(NSArray *) returnArray;
//@property (nonatomic, strong) NSArray *returnArray;
ClassB.m
@implementation ClassB
+(NSArray *) returnArray
{
NSArray *locationArray = @[@"Place1", @"Place2"];
return locationArray;
}
ViewController.m
- (void)viewDidLoad
{
NSArray *location = [ClassB returnArray];
NSLog (@"The count of the location is %d", [location count]);
NSLog (@"The second item in testArray is %@", location[1]);
}
實例方法:查看答案後
ClassB.h
*/
{
@private
NSArray *returnArray;
}
- (void)setReturnArray:(NSArray*)returnArray;
-(NSArray *) returnArray;
*/
@property (nonatomic, strong) NSArray *returnArray;
@end
ClassB.m - no change
ViewController.h - no change
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
//Create instance of ClassB
ClassB *classB = [ClassB new];
//Access the instance of returnArray
NSArray *location = [classB returnArray];
NSLog (@"The count of the location is %d", [location count]);
NSLog (@"The second item in testArray is %@", location[1]);
}
我不確定你的問題是什麼。您正在調用返回數組的類方法,並且您正在獲取數組。財產與它有什麼關係?屬性只是類的實例上的getter/setter方法的簡寫。 – jrturton