Replace array display method?

I am curious how I can override the description method that is used when you do the following (see below) for an object. I basically want to format the output better, but I'm not sure how I can configure this.

NSLog(@"ARRAY: %@", myArray);

many thanks

EDIT_001

Although a subclass of NSArray would work, I decided that I would add a category to NSArray (not using it before) Here's what I added ...

// ------------------------------------------------------------------- **
// CATAGORY: NSArray
// ------------------------------------------------------------------- **
@interface NSArray (displayNSArray)
    -(NSString*)display;
@end

@implementation NSArray (displayNSArray)
-(NSString*)display {
    id eachIndex;
    NSMutableString *outString = [[[NSMutableString alloc] init] autorelease];
    [outString appendString:@"("];
    for(eachIndex in self) {
        [outString appendString:[eachIndex description]];
        [outString appendString:@" "];
    }
    [outString insertString:@")" atIndex:[outString length]-1];
    return(outString);
}
@end

Gary

+3
source share
3 answers

If you do this a lot, the easiest way to reformat the mapping of your array would be to add a new category prettyPrintto the NSArray class.

@interface NSArray ( PrettyPrintNSArray )
- (NSSTring *)prettyPrint;
@end

@implementation NSArray ( PrettyPrintNSArray )
- (NSString *)prettyPrint {
    NSMutableString *outputString = [[NSMutableString alloc] init];
    for( id item in self ) {
        [outputString appendString:[item description]];
    }
    return outputString;
}
@end

Obviously, you need to modify the for loop to get the formatting the way you want.

+2
source

, myArray NSArray/NSMutableArray.

NSLog() @ , -description:. , NSObject, Cocoa. -description: NSString, , , NSLog (@ "@", anyObject) . , .

NSMutableArray -description: . NSMutableArray.

NSObject -description: . Apple docs.

+2

:

NSString supports format characters defined for the ANSI function C functionprintf (), plus' @ for any object. If the object responds to the descriptionWithLocale message: NSString sends this message to retrieve the text view, otherwise it sends a description message.

So, in order to configure the conversion of an array to a string, you must change the NSArray descriptionWithLocale: implementation. Here is an example of how you can replace an object method at runtime.

+1
source

Source: https://habr.com/ru/post/1727356/


All Articles