NSDictionary에 부울 값을 추가하려면 어떻게 해야 합니까?
정수를 위해서라면NSNumber
하지만 YES와 NO는 객체가 아닌 것 같습니다.A.F.A.I.K.개체만 에 추가할 수 있습니다.NSDictionary
,그렇죠?
불리언을 위한 포장지 클래스를 찾을 수 없었습니다.없나요?
NSNumber를 사용합니다.
그 안에...그리고 숫자...정수 등을 사용하는 것처럼 불리언을 사용하는 방법.
NSNumber 클래스 참조:
// Creates and returns an NSNumber object containing a
// given value, treating it as a BOOL.
+ (NSNumber *)numberWithBool:(BOOL)value
그리고:
// Returns an NSNumber object initialized to contain a
// given value, treated as a BOOL.
- (id)initWithBool:(BOOL)value
그리고:
// Returns the receiver’s value as a BOOL.
- (BOOL)boolValue
이후의 새로운 구문Apple LLVM Compiler 4.0
dictionary[@"key1"] = @(boolValue);
dictionary[@"key2"] = @YES;
구문이 변환됩니다.BOOL
로.NSNumber
에게 허용되는 것.NSDictionary
.
리터럴로 선언하고 clang v3.1 이상을 사용하는 경우 리터럴로 선언하려면 @NO / @YES를 사용해야 합니다.예.
NSMutableDictionary* foo = [@{ @"key": @NO } mutableCopy];
foo[@"bar"] = @YES;
자세한 내용은 다음을 참조하십시오.
http://clang.llvm.org/docs/ObjectiveCLiterals.html
jcampbell1이 지적했듯이 NSNumbers에 대해 문자 구문을 사용할 수 있습니다.
NSDictionary *data = @{
// when you always pass same value
@"someKey" : @YES
// if you want to pass some boolean variable
@"anotherKey" : @(someVariable)
};
사용해 보십시오.
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setObject:[NSNumber numberWithBool:TRUE] forKey:@"Pratik"];
[dic setObject:[NSNumber numberWithBool:FALSE] forKey:@"Sachin"];
if ([dic[@"Pratik"] boolValue])
{
NSLog(@"Boolean is TRUE for 'Pratik'");
}
else
{
NSLog(@"Boolean is FALSE for 'Pratik'");
}
if ([dic[@"Sachin"] boolValue])
{
NSLog(@"Boolean is TRUE for 'Sachin'");
}
else
{
NSLog(@"Boolean is FALSE for 'Sachin'");
}
출력은 다음과 같습니다.
'Pratik'의 부울은 TRUE입니다.
'Sachin'의 부울은 FALSE입니다.
언급URL : https://stackoverflow.com/questions/903906/how-can-i-add-a-boolean-value-to-a-nsdictionary
'programing' 카테고리의 다른 글
Firebase를 사용하여 이름 속성별로 사용자 가져오기 (0) | 2023.06.29 |
---|---|
T-SQL을 사용하여 날짜/시간 가져오기 (0) | 2023.06.29 |
Mongodb는 배열 필드의 크기 합계입니다. (0) | 2023.06.24 |
TinyMCE의 사용자 지정 형식 div가 이전 div와 병합 (0) | 2023.06.24 |
Java 8 날짜 시간 유형이 Spring Boot과 함께 객체로 직렬화됨 (0) | 2023.06.24 |