Parsing a Java Properties file in Objective-C for iPhone

后端 未结 6 911
情话喂你
情话喂你 2021-01-18 19:09

I\'m looking for a way in the iPhone SDK to read in a Properties file (not the XML flavor) for example this one:

# a comment
! a comment

a = a string
b = a          


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-18 19:59

    I've ended with this solution if anybody is interested :

    @interface NSDictionary (PropertiesFile)
    
    + (NSDictionary *)dictionaryWithPropertiesFile:(NSString *)file;
    
    @end
    
    @implementation NSDictionary (PropertiesFile)
    
    + (NSDictionary *)dictionaryWithPropertiesFile:(NSString *)file {
        NSError *error = nil;
        NSString *propertyFileContent = [[NSString alloc] initWithContentsOfFile:file encoding:NSUTF8StringEncoding error:&error];
        if (error) return nil;
    
        NSArray *properties = [propertyFileContent componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
        if (properties.count == 0) return nil;
    
        NSMutableDictionary *result = [[NSMutableDictionary alloc] initWithCapacity:properties.count];
        for (NSString *propertySting in properties) {
            NSArray *property = [propertySting componentsSeparatedByString:@"="];
    
            if (property.count != 2) continue;
    
            [result setObject:property[1] forKey:property[0]];
        }
        return result.allKeys.count > 0 ? result : nil;
    }
    
    @end
    

提交回复
热议问题