2016-10-17 6 views
0

가 여기JSON 모델 - 방법 "arrayOfModelsFromDictionaries"

@interface ProductModel : JSONModel 
@property (assign, nonatomic) int id; 
@property (strong, nonatomic) NSString* name; 
@property (assign, nonatomic) float price; 
@property (assign, nonatomic) BOOL isOK; 
@end 

다음 다음과 같이 내가 JSONModel을 만든

[{ 
    "id": 1, 
    "name":"Soup", 
    "price":200, 
    "isOK":1 
}, 
{ 
    "id": 2, 
    "name":"Salad", 
    "price":100, 
    "isOK":0 
}] 

내 JSON 데이터를 사용하는 경우 배열에 모든 객체를 추가하지

NSArray* modelsArray = [ProductModel arrayOfModelsFromDictionaries:objects]; 

이제 내가 원하는 것은

if(isOK) 
{ 
    // then add the model into the modelsArray 
} else { 
    // then don't add the model into the modelsArray 
} 

modelsArray를 반복 한 다음 isOK를 기준으로 객체를 하나씩 제거하지 않고도이 논리를 모델 파일 내 어딘가에 작성할 수 있습니까?

+0

isok 값의 모델링 영역에서 개체를 제거 하시겠습니까? –

+0

@balkaran singh thats corrects, 그러나 배열을 다시 반복하지 않고 – Haider

+0

이것을 위해 NSPredicate를 사용할 수 있습니다. –

답변

1
NSArray* modelsArray = [ProductModel arrayOfModelsFromDictionaries:objects];  
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isOK == 1"]; 
NSArray* filtedArray = [modelsArray filteredArrayUsingPredicate:predicate]; 
+0

모델 파일에 true 또는 false를 반환하고 객체가 배열에 추가되는지 여부를 결정하는 함수가있을 수 있는지 궁금합니다. 대답을 주셔서 감사합니다 – Haider

2
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF['isOK'] CONTAINS '1'"]; 
NSArray* filted_Array_OK = [modelarray filteredArrayUsingPredicate:predicate]; 
NSLog(@"%@",filted_Array_OK); 

NSArray* filted_Array_NOT_OK = [modelarray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF['isOK'] CONTAINS '0'"]]; 
NSLog(@"%@",filted_Array_NOT_OK); 

여기 modelArray는 당신이이 형식 값이 2 개의 다른 배열을 가지고이 코드 isOK = 0 에게 isOK = 1

당신의 모든 값을 포함 isOK = 1 및 isOK = 0 이제 원하는 배열을 직접 사용할 수 있습니다. 당신이 할 수있는 빠른 열거를 사용 filted_Array_OK

(
     { 
     id = 1; 
     isOK = 1; 
     name = Soup; 
     price = 200; 
    }, 
     { 
     id = 3; 
     isOK = 1; 
     name = peace; 
     price = 900; 
    } 
) 

filted_Array_NOT_OK

(
     { 
     id = 2; 
     isOK = 0; 
     name = cake; 
     price = 200; 
    }, 
     { 
     id = 4; 
     isOK = 0; 
     name = bread; 
     price = 800; 
    } 
) 
+0

좋아, 내가 사실 또는 false를 반환하고 객체가 배열에 추가 될 것인지 아닌지를 결정하는 함수가 모델 파일에있을 수 있는지 궁금합니다. 어쨌든 상세한 답변을 주셔서 감사합니다. – Haider

+0

@Haider 나는 2 개의 배열을 제공하기 때문에 언제든지 쉽게 사용할 수 있습니다. –

0

:

출력.

for (ProductModel* productModel in objects) { 
    if(productModel.isOK){ 
    [modelarray addOjbect:productModel]; 
    } 
} 
+0

그게 지금하고있는 일 .. – Haider

+0

뭘하고 싶은거야? – KKRocks

2

예, NSPredicate를 사용할 수 있습니다.

NSArray* modelsArray = [ProductModel arrayOfModelsFromDictionaries:objects];  
    [NSPredicate predicateWithFormat:@"SELF.isOK == %@ && SELF.isOK != nil", @YES]; 
    NSArray* filtedArray = [modelsArray filteredArrayUsingPredicate:predicate];