Re: printing arrays
Re: printing arrays
- Subject: Re: printing arrays
- From: "Gerriet M. Denkmann" <email@hidden>
- Date: Fri, 09 Nov 2012 12:27:35 +0700
On 3 Nov 2012, at 22:42, Kyle Sluder <email@hidden> wrote:
> On Nov 2, 2012, at 10:18 PM, "Gerriet M. Denkmann" <email@hidden> wrote:
>
>>
>> On 3 Nov 2012, at 00:35, Kyle Sluder <email@hidden> wrote:
>>
>>> If this is just for debugging purposes, you could swizzle -[NSArray
>>> description] and -[NSDictionary description].
>>
>> I tried a Category for NSArray like:
>
> You must never use a category to replace an existing method implementation. Swizzling is the only approach that will work.
About swizzling I found: <http://darkdust.net/writings/objective-c/method-swizzling> and <http://www.cocoawithlove.com/2008/03/supersequent-implementation.html>.
What to swizzle: The "String Programming Guide" says: %@ prints "Objective-C object, printed as the string returned by descriptionWithLocale: if available, or description otherwise."
In my case: NSArray, NSSet, NSDictionary all have descriptionWithLocale: so this had to be swizzled.
Easy way: just return [self debugDescription] which is readable.
Disadvantage: it does not print in a nice indented way like the original descriptionWithLocale: does.
So I created for the 3 classes of concern:
- (NSString *)niceDescriptionIndented: (NSUInteger)indent
which prints nice and indented.
- (NSString *)niceDescriptionIndented: (NSUInteger)indent
{
NSMutableString *indenStr = [ NSMutableString string ];
for( NSUInteger i = 0; i < indent; i++ ) [ indenStr appendString: @"\t" ];
NSMutableString *outStr = [ NSMutableString string ];
[ outStr appendFormat: @"%@ (%lu)", [self class], [self count] ];
[ outStr appendString: @"\n" ];
[ outStr appendString: indenStr ];
[ outStr appendString: @"[" ];
[ outStr appendString: @"\n" ];
for( id item in self )
{
[ outStr appendString: indenStr ];
[ outStr appendString: @"\t" ];
if ( [ item respondsToSelector: @selector(niceDescriptionIndented:) ] )
{
[ outStr appendString: [item niceDescriptionIndented: indent + 1] ];
}
else
{
[ outStr appendString: [item description] ];
};
[ outStr appendString: @"\n" ];
};
[ outStr appendString: indenStr ];
[ outStr appendString: @"]" ];
return outStr;
}
The NSSet, NSDictionary methods are (almost) identical.
Kind regards (and thanks for pushing me in the right direction!)
Gerriet.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden