簡體   English   中英

iOS-查找對象逆的最佳方法

[英]iOS - Best way to find object inverse

我正在編寫一個基本上遍歷NSManagedObject對象並將其轉換為JSON字典的遞歸方法。 我已經完成了大部分工作,但是我遇到一個問題,當涉及對象的逆時,該方法將陷入無限循環。

例如,假設該方法以一個具有Job類的對象開始,並且在Job對象內部有一個名為Surveys的屬性。 調查是一個NSSet,其中包含多個JobSurvey對象。 每個JobSurvey對象都包含一個與原始Job對象相反的逆,並且該屬性稱為“ Job”。

當我通過我的方法運行它時,它將通過進入作業開始無限循環並開始處理每個屬性。 該方法進入Surveys屬性后,將再次調用該方法以按預期處理每個JobSurvey對象。 然后,該方法處理每個屬性,直到它到達Job(反向)對象。 到那時,它將繼續處理該對象,從而創建無限循環。

關於如何解決此問題有任何想法嗎? 我試圖編寫這種方法而不必使用對象映射創建自定義對象類,因為它需要能夠與我傳遞給它的任何類型的對象一起使用。 下面是我到目前為止的代碼。

- (NSDictionary *)encodeObjectsForJSON:(id)object
{
    NSMutableDictionary *returnDictionary = [[NSMutableDictionary alloc] init];

    // get the property list for the object
    NSDictionary *props = [VS_PropertyUtilities classPropsFor:[object class]];

    for (NSString *key in props) {

        // get the value for the property from the object
        id value = [object valueForKey:key];

        // if the value is just null, then set a NSNull object
        if (!value) {

            NSNull *nullObj = [[NSNull alloc] init];
            [returnDictionary setObject:nullObj forKey:key];

        // if the value is an array or set, then iterate through the array or set and call this method again to encode it's values
        } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSSet class]]) {

            NSMutableArray *retDicts = [[NSMutableArray alloc] init];

            // encode each member of the array to a JSON dictionary
            for (id val in value) {
                [retDicts addObject:[self encodeObjectsForJSON:val]];
            }

            // add to the return dictionary
            [returnDictionary setObject:retDicts forKey:key];

        // else if this is a foundation object, then set it to the dictionary
        } else if ([value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSNumber class]] || [value isKindOfClass:[NSNull class]] || [value isKindOfClass:[NSDate class]]) {

            [returnDictionary setObject:value forKey:key];

        // else this must be a custom object, so call this method again with the value to try and encode it
        } else {

            NSDictionary *retDict = [self encodeObjectsForJSON:value ];
            [returnDictionary setObject:retDict forKey:key];
        }
    }

    return returnDictionary;
}

這就是我所做的。 它與您要實現的目標相似。

鏈接到代碼

它比我想您要查找的要明確得多,但我想我建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM