How to find unused ivars in Xcode
Asked Answered
V

3

6

Sometimes I declare an ivar but after a while I am no longer using it. I would like to remove this sort of cruft from my code, but I cannot find a warning that will show me my unused ivars.

Is there a tool or built in feature of Xcode that will allow me to find all of my unused ivars?

I see that the static analyzer has CLANG_ANALYZER_OBJC_UNUSED_IVARS, but it does not seem to do anything.

@implementation AppDelegate
{
@private
    BOOL _foo; // Never read or written to
}

Runing the analyzer in Xcode 5 with CLANG_ANALYZER_OBJC_UNUSED_IVARS (unused ivars) set to YES never produces a warning.

Veator answered 13/1, 2014 at 22:59 Comment(3)
Delete (or comment out) the ivar, compile, and see if there are any complaints.Lifegiving
Yep that would work, but for a large project that is tedious, and I was hoping for an automated tool that look through all classes without me having to modify code.Veator
The other option is to not add so dang many ivars in the first place.Lifegiving
H
4

Based on the relevant Clang source code and a couple of quick tests, it seems that the analyzer does not look at ivars that are not both declared in the @interface and marked @private.

@interface Igloo : NSObject
{
    NSString * address;    // No warning
    @private
    NSInteger radius;    // Warning
}
@end

@implementation Igloo
{
    NSInteger numWindows;    // No warning
    @private    // Has no real effect, of course; just testing
    NSString * doormatText;    // No warning
}

@end

I suggest filing a bug/submitting a patch.

Henke answered 13/1, 2014 at 23:25 Comment(3)
are you saying analyzer only look at ivars are both declared in the @interface and marked @private? double not confused me..Perri
Right, @BryanChen, what you said. BOOL analyzed = (declaredInInterface && markedPrivate);Henke
Seems odd, putting iVars in the @interface seems to be a deprecated pattern.Meatman
T
1

In Xcode from product menu click on analyze... It will show you unused variables. This will also tell you about dead code.

Tuberculosis answered 13/1, 2014 at 23:10 Comment(1)
Analyze definitely needs more awarenessOestriol
V
1

It appears that the static analyzer option only works if you declare the ivar in the header file.

This generates the analyzer warning correctly:

// AppDelegate.h
@interface AppDelegate : NSObject <UIApplicationDelegate>
{
    BOOL _foo; // never read or written
}
@end

Neither of these generates any sort of analyzer warning:

//  AppDelegate.m
@interface AppDelegate ()
{
@private
    BOOL _goo; // never read or written
}
@end

@implementation AppDelegate
{
@private
    BOOL _hoo; // never read or written
}
@end

So it looks like you cannot use the modern syntax to keep ivars in the .m file if you want to check for unused ivars.

Veator answered 13/1, 2014 at 23:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.