简体   繁体   中英

Static analysis warns of init not called when loading from NSKeyedUnarchiver unarchiveObjectWithData

I'm receiving a static analysis error, and I'm not sure if it can be safely ignored, or if I can improve the design to remove it without to much change, this is legacy code.

This does NOT use ARC.

-(id) initCustom{
     NSString* key = @"foo";

    NSData* objectData = nil;
    objectData = [[NSUserDefaults standardUserDefaults]   objectForKey:key];
    if( objectData != nil)
    {
        //If this path is taken the error occurs
        self = [NSKeyedUnarchiver unarchiveObjectWithData:objectData];
    }
    else
    {
        self = [super init];
    }

    if (self)
    {
        //Static analysis warns here
        m_fiz   = [[NSString alloc] initWithString:@"bar"]; 
        //Instance variable used while 'self' is not set to the result of '[(super or self) init....]'

    }
}

My understanding is that [NSKeyedUnarchiver unarchiveObjectWithData:objectData] will cause the "initWithCoder" to be called. This object implements NSCoding , and has the proper methods required by NSCoding implemented.

Is this a false positive from the static analysis, or can I make it better?

The compiler is warning because that is a bizarre way of doing this. :)

Move the "read from defaults or create new" logic into a class method. That will both fix the compiler warning message and be a more consistent pattern.

+ (instancetype) defaultThingamahoover
{
     ... check defaults database and unarchive ...
     ... or return new ....
}

BTW: In general, you don't want to shove anything large into the defaults database. It is pretty atypical to archive an object and stick it in there. The defaults database is generally intended for small key/value pairs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM