LoginSignup
7

More than 5 years have passed since last update.

デバッグビューを作ってみる

Posted at

NSLogに出力するデバッグ文字列たちをアプリのViewに出したい。
Xcode触りながらテストする分にはあんま需要はないけど
諸事情でXcode触れない環境下での疎通テストに等使ったりした。

--

つかいかた

  1. DebugViewのソースを用意する
  2. xibをつくる(DebugView.xib)
  3. xibの中にUIView入れる
  4. UIViewのCustom ClassにDebugViewを入れてひもづける
  5. DebugViewにUITextViewを入れてIBOutletのプロパティにひもづける
  6. DEBUG_LOG(@"hoge"); でつかう

補足

  • テキスト消去と画面クローズのIBActionあるので適当に。
  • ログ出すたびに上に出るので、うざかったら「[DebugView open];\」の行を消して applicationDidBecomeActive:applicationあたりに「[DebugView open]」書いておくと ホーム画面経由でアプリ復帰した時にでるのでウザさがマシになる。

--

DebugView.h
#import <UIKit/UIKit.h>

@interface DebugView : UIView

#define DEBUG_LOG(A, ...){\
[DebugView open];\
[DebugView addText:[NSString stringWithFormat:A, ## __VA_ARGS__]];\
NSLog(@"%@",[NSString stringWithFormat:A, ## __VA_ARGS__]);}

+ (DebugView*)instance;
+ (void)open;
+ (void)close;
+ (void)addText:(NSString*)value;
+ (void)removeText;
@end
DebugView.m
#import "DebugView.h"

@implementation DebugView{
    __weak IBOutlet UITextView *textView;
}

#pragma mark - static

static BOOL isOpen;
static DebugView *sharedView = nil;

+ (DebugView*)instance {
    @synchronized(self){
        if(sharedView == nil)
            sharedView = (DebugView*)[[[NSBundle mainBundle] loadNibNamed:@"DebugView" owner:nil options:nil] objectAtIndex:0];
    }
    return sharedView;
}
+ (id)allocWithZone:(NSZone *)zone{
    @synchronized(self) {
        if(sharedModel == nil)  {
            sharedModel = [super allocWithZone:zone];
            return sharedModel;
        }
    }
    return nil;
}

+ (void)open{
    if(isOpen) return;
    isOpen = YES;
    UIWindow* window = [UIApplication sharedApplication].keyWindow;
    if(!window)window = [[UIApplication sharedApplication].windows objectAtIndex:0];
    [window addSubview:[DebugView instance]];
}

+ (void)close{
    if(!isOpen) return;
    isOpen = NO;
    [[DebugView instance] removeFromSuperview];
}

+ (void)addText:(NSString*)value{
    [[DebugView instance] addText:value];
}

+ (void)removeText{
    [[DebugView instance] removeText];
}

#pragma mark - public

- (void)addText:(NSString*)value{
    NSString* str = [NSString stringWithFormat:@"%@\n%@", textView.text, value];
    textView.text = str;
    textView.textColor = [UIColor whiteColor];
    [self setNeedsDisplay];
}

- (void)removeText{
    textView.text = @"";
    [self setNeedsDisplay];
}

#pragma mark - IBAction

- (IBAction)onTouchDeleteTextButton:(id)sender {
    [self removeText];
}

- (IBAction)onTouchCloseButton:(id)sender {
    [DebugView close];
}
@end

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7