arkaeologic
arkaeologic

Reputation: 85

obj c class memory management

I have extended UIView in order to implement some unique functionality. Along with this, I have included several objects as properties and defined them in the initialiser as defaults. This means that every object that extends this class, Graphics.m, will have these objects instantiated and available, things like default interface colours.

My question is, if I have a large number of objects, will the fact I have these defaults instantiated in every object (they may go unused in some objects) seriously affect the app's performance?

I am running the latest versions of Xcode and iOS.

Thanks for reading.

Upvotes: 0

Views: 63

Answers (1)

user557219
user557219

Reputation:

If I have a large number of objects, will the fact I have these defaults instantiated in every object (they may go unused in some objects) seriously affect the app's performance?

It depends on the size of these properties and whether the frameworks internally cache instances.

What you could do in your case is to keep defaults in variables with static storage duration and have your properties point to those variables when an instance is initialised. In this case, if those properties aren’t changed after initialisation then they all point to the same objects. For example:

// ARKGraphicsView.m

static UIColor *_ARKGraphicsViewDefaultForegroundColour = nil;
static UIColor *_ARKGraphicsViewDefaultBackgroundColour = nil;
static UIColor *_ARKGraphicsViewDefaultBorderColour = nil;

@implementation ARKGraphicsView

+ (void)initialize {
    if (self == [ARKGraphicsView class]) {
        // This code is executed only once,
        // when the class receives its first message
        _ARKGraphicsViewDefaultForegroundColour = [UIColor …];
        _ARKGraphicsViewDefaultBackgroundColour = [UIColor …];
        _ARKGraphicsViewDefaultBorderColour = [UIColor …];
    }
}

- (id)initWith… {
    self = [super initWith…];
    if (self) {
        _foregroundColour = _ARKGraphicsViewDefaultForegroundColour;
        _backgroundColour = _ARKGraphicsViewDefaultBackgroundColour;
        _borderColour = _ARKGraphicsViewDefaultBorderColour;
    }
    return self;
}

…

@end

If the program creates 100 instances of this class and no colours are changed by those instances, there will be only three UIColor instances—those kept in the _ARK*Colour variables.

Upvotes: 1

Related Questions