Search code examples
objective-cnsstringstatic-methods

Objective c / How do I call a user-implemented static function into the nsstring class?


+ (NSString *)dictionaryToJson:(NSDictionary *)dic
{
    NSString *result = @"";
    NSError *err;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&err];
    
    if(! jsonData) {
        NSLog(@"Error: %@", err);
    } else {
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        result = jsonString;
    }
    
    return result;
}

The functions that we define here are

[body appendData:[[NSString dictionaryToJson:jsonBody] dataUsingEncoding:NSUTF8StringEncoding]];

I don't think you understood the function call from objc yet. Please help me.


Solution

  • here you'd typically extend the class using a category. See e.g. https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html

    // Header file
    // Something like NSString+JSONAdditions.h
    @interface NSString (JSONAdditions)
    
    + (NSString *)dictionaryToJson:(NSDictionary *)dic;
    
    @end
    
    // Implementation file
    // Something like NSString+JSONAdditions.m
    @implementation NSString (JSONAdditions)
    
    + (NSString *)dictionaryToJson:(NSDictionary *)dic
    {
        NSString *result = @"";
        NSError *err;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&err];
    
        if(! jsonData) {
            NSLog(@"Error: %@", err);
        } else {
            NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            result = jsonString;
        }
    
        return result;
    }
    
    @end
    

    Now you can use the code as in the snippet you provided. FWIW in Xcode do this using

    File -> New -> File ... -> Objective-C file