Objective-C에서 클래스 레벨 속성을 선언하려면 어떻게 해야 합니까?
당연한 얘기겠지만 Objective-C에서 클래스 속성을 어떻게 신고해야 할지 모르겠어요.
나는 학급별로 사전을 캐시해야 하는데, 그 사전이 학급에 어떻게 배치되어 있는지 궁금해요.
Objective-C에서 속성은 특정 의미를 가지지만 정적 변수에 해당하는 것을 의미한다고 생각합니다.예를 들어 Foo의 모든 유형에 대해 하나의 인스턴스만 있습니까?
Objective-C에서 클래스 함수를 선언하려면 - 대신 + 프레픽스를 사용합니다.그러면 구현은 다음과 같습니다.
// Foo.h
@interface Foo {
}
+ (NSDictionary *)dictionary;
// Foo.m
+ (NSDictionary *)dictionary {
static NSDictionary *fooDict = nil;
if (fooDict == nil) {
// create dict
}
return fooDict;
}
이 솔루션을 사용하고 있습니다.
@interface Model
+ (int) value;
+ (void) setValue:(int)val;
@end
@implementation Model
static int value;
+ (int) value
{ @synchronized(self) { return value; } }
+ (void) setValue:(int)val
{ @synchronized(self) { value = val; } }
@end
싱글턴 패턴을 대체하기 위해 매우 유용하다는 것을 알게 되었습니다.
이를 사용하려면 점 표기법으로 데이터에 액세스하기만 하면 됩니다.
Model.value = 1;
NSLog(@"%d = value", Model.value);
WWDC 2016/XCode 8 (LLVM 세션의 새로운 기능 @5:05).클래스 속성은 다음과 같이 선언할 수 있습니다.
@interface MyType : NSObject
@property (class) NSString *someString;
@end
NSLog(@"format string %@", MyType.someString);
클래스 속성은 합성되지 않습니다.
@implementation
static NSString * _someString;
+ (NSString *)someString { return _someString; }
+ (void)setSomeString:(NSString *)newString { _someString = newString; }
@end
클래스 레벨에 상당하는 것을 찾고 있는 경우@property
그러면 정답은 '그런 건 없다'입니다.하지만 기억하세요.@property
어쨌든 통사적인 설탕일 뿐이고 적절한 이름을 가진 오브젝트 메서드를 만들 뿐입니다.
다른 사용자가 말한 것처럼 구문만 약간 다른 정적 변수에 액세스하는 클래스 메서드를 만들 수 있습니다.
스레드 세이프한 방법은 다음과 같습니다.
// Foo.h
@interface Foo {
}
+(NSDictionary*) dictionary;
// Foo.m
+(NSDictionary*) dictionary
{
static NSDictionary* fooDict = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
// create dict
});
return fooDict;
}
이러한 편집에 의해 fooDict는 한 번만 작성됩니다.
Apple 문서: "dispatch_once - 응용 프로그램 수명 동안 블록 개체를 한 번만 실행합니다."
Xcode 8에서 Objective-C는 클래스 속성을 지원하게 되었습니다.
@interface MyClass : NSObject
@property (class, nonatomic, assign, readonly) NSUUID* identifier;
@end
클래스 속성은 합성되지 않으므로 구현 내용을 직접 작성해야 합니다.
@implementation MyClass
static NSUUID*_identifier = nil;
+ (NSUUID *)identifier {
if (_identifier == nil) {
_identifier = [[NSUUID alloc] init];
}
return _identifier;
}
@end
클래스 속성에 액세스하려면 클래스 이름의 일반 닷 구문을 사용합니다.
MyClass.identifier;
속성은 클래스가 아닌 개체에만 값을 가집니다.
클래스의 모든 객체에 대해 무언가를 저장해야 하는 경우 글로벌 변수를 사용해야 합니다.선언함으로써 숨길 수 있습니다.static
를 참조해 주세요.
오브젝트 간의 특정 관계를 사용하는 것도 고려할 수 있습니다.마스터의 역할은 클래스의 특정 오브젝트에 속하고 다른 오브젝트를 이 마스터에 링크합니다.마스터는 사전을 단순한 속성으로 보유합니다.나는 코코아 애플리케이션의 뷰 계층에 사용되는 트리를 생각한다.
다른 옵션은 '클래스' 사전과 이 사전과 관련된 모든 개체 집합으로 구성된 전용 클래스의 개체를 만드는 것입니다. 게 요.NSAutoreleasePool
코코아에서.
Xcode 8부터는 Berbie가 응답한 클래스 속성 속성을 사용할 수 있습니다.
단, 구현에서는 iVar 대신 정적 변수를 사용하여 클래스 속성에 대해 클래스 getter와 setter를 모두 정의해야 합니다.
Sample.h
@interface Sample: NSObject
@property (class, retain) Sample *sharedSample;
@end
샘플.m
@implementation Sample
static Sample *_sharedSample;
+ ( Sample *)sharedSample {
if (_sharedSample==nil) {
[Sample setSharedSample:_sharedSample];
}
return _sharedSample;
}
+ (void)setSharedSample:(Sample *)sample {
_sharedSample = [[Sample alloc]init];
}
@end
클래스 레벨 속성이 많은 경우 싱글톤 패턴이 순서대로 있을 수 있습니다.다음과 같은 경우:
// Foo.h
@interface Foo
+ (Foo *)singleton;
@property 1 ...
@property 2 ...
@property 3 ...
@end
그리고.
// Foo.m
#import "Foo.h"
@implementation Foo
static Foo *_singleton = nil;
+ (Foo *)singleton {
if (_singleton == nil) _singleton = [[Foo alloc] init];
return _singleton;
}
@synthesize property1;
@synthesize property2;
@synthesise property3;
@end
이제 다음과 같이 클래스 수준의 속성에 액세스합니다.
[Foo singleton].property1 = value;
value = [Foo singleton].property2;
[심플한 솔루션 테스트]Swift 클래스에서 정적 변수를 생성하여 Objective-C 클래스에서 호출할 수 있습니다.
언급URL : https://stackoverflow.com/questions/695980/how-do-i-declare-class-level-properties-in-objective-c
'programing' 카테고리의 다른 글
RSA 개인 키에 대한 Opensh 개인 키 (0) | 2023.04.21 |
---|---|
WPF 버튼을 ViewModelBase 명령어에 바인드하려면 어떻게 해야 합니까? (0) | 2023.04.21 |
짧은 Git 버전 해시를 가져옵니다. (0) | 2023.04.21 |
Azure 500 내부 서버 오류를 디버깅하는 방법 (0) | 2023.04.21 |
6.5인치 디스플레이의 앱스토어 스크린샷 크기는 어떻게 됩니까? (0) | 2023.04.21 |