programing

Objective C의 사유 재산

nasanasas 2020. 11. 11. 20:15
반응형

Objective C의 사유 재산


Objective C에서 개인 속성을 선언하는 방법이 있습니까? 목표는 특정 메모리 관리 체계를 구현하는 합성 된 게터 및 세터의 이점을 누리지 만 공개되지 않는 것입니다.

범주 내에서 속성을 선언하려고하면 오류가 발생합니다.

@interface MyClass : NSObject {
    NSArray *_someArray;
}

...

@end

@interface MyClass (private)

@property (nonatomic, retain) NSArray   *someArray;

@end

@implementation MyClass (private)

@synthesize someArray = _someArray;
// ^^^ error here: @synthesize not allowed in a category's implementation

@end

@implementation MyClass

...

@end

나는 이와 같은 개인 속성을 구현합니다.

MyClass.m

@interface MyClass ()

@property (nonatomic, retain) NSArray *someArray;

@end

@implementation MyClass

@synthesize someArray;

...

그게 전부입니다.


A. 완전히 개인용 변수를 원할 경우. 재산을주지 마십시오.
B. 클래스 캡슐화에서 외부에서 액세스 할 수있는 읽기 전용 변수를 원하는 경우 전역 변수와 속성의 조합을 사용합니다.

//Header    
@interface Class{     
     NSObject *_aProperty     
}

@property (nonatomic, readonly) NSObject *aProperty;

// In the implementation    
@synthesize aProperty = _aProperty; //Naming convention prefix _ supported 2012 by Apple.

readonly 한정자를 사용하여 이제 외부에서 속성에 액세스 할 수 있습니다.

Class *c = [[Class alloc]init];    
NSObject *obj = c.aProperty;     //Readonly

그러나 내부적으로는 Class 내부에 aProperty를 설정할 수 없습니다.

// In the implementation    
self.aProperty = [[NSObject alloc]init]; //Gives Compiler warning. Cannot write to property because of readonly modifier.

//Solution:
_aProperty = [[NSObject alloc]init]; //Bypass property and access the global variable directly

As others have indicated, (currently) there is no way to truly declare a private property in Objetive-C.

One of the things you can do to try and "protect" the properties somehow is to have a base class with the property declared as readonly and in your subclasses you can redeclare the same property as readwrite.

Apple's documentation on redeclared properties can be found here: http://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW19


It depends what you mean by "private".

If you just mean "not publicly documented", you can easily enough use a class extension in a private header or in the .m file.

If you mean "others are not able to call it at all", you're out of luck. Anyone can call the method if they know its name, even if it is not publicly documented.

참고URL : https://stackoverflow.com/questions/5643130/private-property-in-objective-c

반응형