1. 程式人生 > >[Object-c] Log(輸出陣列和字典的中文內容)

[Object-c] Log(輸出陣列和字典的中文內容)

#import <Foundation/Foundation.h>

@interface NSArray (Log)

@end

@interface NSDictionary (Log)

@end



#import "NSArray+Log.h"

@implementation NSArray (Log)
//這個方法是專門針對國際化語言除錯使用的,一旦實現,再輸出陣列,就會呼叫此方法。
//因為是除錯使用的,只要實現分類方法,就會被呼叫,不需要import
- (NSString *)descriptionWithLocale:(id)locale
{
    NSMutableString *strM = [NSMutableString stringWithString:@"(\n"];
    
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [strM appendFormat:@"\t%@,\n", obj];
    }];
   
    [strM appendString:@")"];
   
    return strM.copy;
}

@end

@implementation NSDictionary (Log)

- (NSString *)descriptionWithLocale:(id)locale
{
    NSMutableString *strM = [NSMutableString stringWithString:@"{\n"];
   
    [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [strM appendFormat:@"\t%@ = %@;\n", key, obj];
    }];
   
    [strM appendString:@"}\n"];
   
    return strM.copy;
}

@end


//輸出自定義類
// 方便除錯
// 在 iOS 團隊開發中,但是建議在自定義模型中實現此方法!
- (NSString *)description {

    NSDictionary *dict = [self dictionaryWithValuesForKeys:@[@"name", @"age"]];
    return [NSString stringWithFormat:@"<%@: %p> %@", self.class, self, dict];
}